Search code examples
angularangular-routingangular-router

angular routing is not working in angular 19


Why is this routing config not working? The router is trying to go /posts but it should not go to /posts. Currently it is showing a blank page. BlankComponentComponent contains router-outlet and FullComponentComponent contains header, router-outlet and footer.

When user is logged in, then it should use BlankComponentComponent router-outlet otherwise it should use FullComponentComponent. I remember I used this to work in Angular 14.

export const routes: Routes = [
  {
    path: '',
    component: BlankComponentComponent, 
    canActivate: [
      () => {
        return true;
      },
    ],
    children: [
      {
        path: '',
        redirectTo: '/auth',
        pathMatch: 'full',
      },
      {
        path: 'auth',
        children: [...authRoutes],
      },
    ],
  },
  {
    path: '',
    component: FullComponentComponent,
    canActivate: [
      () => {
        return false;
      },
    ],
    children: [
      {
        path: '',
        redirectTo: 'posts',
        pathMatch: 'full',
      },
      {
        path: 'posts',
        loadComponent: () =>
          import('./post/posts/posts.component').then((c) => c.PostsComponent),
      },
    ],
  },
];


Solution

  • The canActivate function is returning false so the component might not be loaded for posts.

    canActivate: [
      () => {
        const router = inject(Router);
        const isAuthorized = false; // calculate this!
        return isAuthorized ? true : router.createUrlTree(['auth']); // <- change this!
      },
    ],