Carlos Cifuentes
AngularJS → Angular reference

$urlRouterProvider.otherwise / redirectTo in modern Angular

otherwise becomes a wildcard route with path '**'. redirectTo accepts a fixed path or, since Angular 18, a function that can use inject().

Before · AngularJS
$urlRouterProvider.when('', '/dashboard');
$urlRouterProvider.otherwise(function ($injector) {
  var auth = $injector.get('AuthService');
  return auth.isLoggedIn() ? '/not-found' : '/login';
});

// ngRoute
$routeProvider.otherwise({ redirectTo: '/dashboard' });
After · Angular
export const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'dashboard' },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'login', component: LoginComponent },
  { path: 'not-found', component: NotFoundComponent },
  {
    path: '**',
    redirectTo: () => (inject(AuthService).isLoggedIn() ? '/not-found' : '/login'),
  },
];

What changes

  • Route order matters: the first match wins, so the wildcard route goes last.
  • The redirect for the empty path needs pathMatch: 'full'; without it the route matches every URL.
  • A redirect function receives the params and query params of the matched route and returns a path or a UrlTree.

Migration tip. In a hybrid app the wildcard is where unknown URLs are handed to the legacy router. Add the Angular not-found page only when the legacy router no longer owns any URL.

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