How to migrate from Angular UI-Router to Angular Router

Hanky Panky
2 min readApr 8, 2021

So, after migrating from AngularJS to Angular-next my team faced trouble like what we need to do with the router system? What if do not have enough time to migrate together with a framework migration? Actually, the answer is do nothing ^_^. But the time has come and google helped me find only classic migration from 1st to 2nd.

After spending some time for investigation I figured out the main issues that I should solve to complete this challenge:

  1. How two routing system can work together and won`t affect each other
  • the answer is easy ^_^, so I just added these ‘outlets’ into app-component
<div ui-view="content"></div> // old
<router-outlet></router-outlet> // new

so, it works! ))) but we have a BUT that works not how we expected it. If we try to move from the ‘old’ page to the ‘new’ we will see that the previous component still exists. And if we have something like this

router.urlService.rules.otherwise({ state: '404' }); // UI-Router
{ path: '**', component: Page404 }, // Angular router

we will see some data and 404-page T_T.

To solve this trouble we should check when changing the routing system and in my case, I have to remove 404 page temporarily while migrating. And create an ‘empty’ component to switch on it when we are switching between routing systems.

These router systems provide us ‘handlers’ to have a possibility to do that I explained above or do something with URL ‘on a flight’ for Angular it is `UrlHandlingStrategy`Interface and for UI-Router it is `config` function:

‘If a UI-Router Module needs to perform some configuration (such as registering parameter types or Transition Hooks) a configFn should be supplied. The function will be passed the UIRouter instance, the module’s Injector, and the module object.’

So in my case, I`ve added this logic into guards:

export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private stateService: StateService) {}

canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

this.stateService.go('empty');

return true;
}
}

and

export function uiRouterConfigFn(router: UIRouter, injector: Injector) {


const authRequiredCriteria = { entering: (state) => state.authenticationRequired };
router.transitionService.onBefore(authRequiredCriteria, (transition) => {
const transition = (transition: Transition, injector) => {
router.navigate(['empty']);
}
return authorize(transition, injector);
});
}

This is very schematic, but the code above in each router iteration applies an empty component into view. If you have a question pls ask I'll appreciate it because it is my first article ^_^

--

--