$stateChangeStart / transition hooks in modern Angular
Global transition hooks become guards attached to the routes they protect.
Before · AngularJS
$transitions.onStart({ to: 'admin.**' }, function (trans) {
var auth = trans.injector().get('AuthService');
if (!auth.isLoggedIn()) {
return trans.router.stateService.target('login');
}
});After · Angularexport const authGuard: CanActivateFn = () => {
const auth = inject(AuthService);
return auth.isLoggedIn() ? true : inject(Router).createUrlTree(['/login']);
};
{
path: 'admin',
canActivate: [authGuard],
loadChildren: () => import('./admin.routes').then(m => m.ADMIN_ROUTES),
}What changes
- canActivate decides if a route can open; canMatch decides if it even exists for this user.
- A guard returns true, false or a redirect, instead of cancelling an event.
- canDeactivate replaces the unsaved-changes checks done in $stateChangeStart.
Migration tip. Both frameworks must use the same AuthService in a hybrid app. A session that exists only on one side is a common source of login bugs.
Related
Planning a migration or a micro-frontend platform?
In a 20-minute call you describe your situation and I tell you how I'd approach it. If it isn't worth doing yet, I'll say so.
Message me on LinkedIn