BadPiggie
BadPiggie

Reputation: 6379

AuthGuard and RedirectTo not working for root path

I am working on a angular application, Which has following URL Paths,

I have added AuthGuard for all routes except auth/login. AuthGuard redirects to auth\login if not authenticated.


app-routing.module.ts

export const Approutes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    component: FullComponent,
    loadChildren: () => import('./pages/pages.module').then(m => m.PagesModule) // loading from pages-routing.ts
  },
  {
    path: 'auth',
    component: PlainComponent,
    children: [
      {
        path: '',
        pathMatch: 'full',
        redirectTo: 'login'
      },
      {
        path: 'login',
        component: LoginComponent
      }
    ]
  },
  {
    path: '**',
    redirectTo: ''
  }
];

pages-routing.ts

export const PagesRoutes: Routes = [
    {
        path: '',
        children: [
            {
                path: '',
                pathMatch: 'full',
                redirectTo: 'courses'
            },
            {
                path: 'courses',
                component: CourseMainPageComponent,
                data: {
                    title: 'My Courses'
                }
            },
            {
                path: 'courses/create',
                component: CourseCreatePageComponent,
                data: {
                    title: 'Create Course'
                }
            },
            {
                path: 'courses/:id',
                component: CourseShowPageComponent,
                data: {
                    title: 'Course Detail'
                }
            },
        ]
    }
];

The Problem

All routes and authGuard works fine. But when I enter the root URL \, I needed to redirect to \courses, But it's not working. Also in root URL \ AuthGuard is not redirecting me to auth\login even.

NOTE I don't get any run-time or compile error.

Upvotes: 2

Views: 1043

Answers (1)

nash11
nash11

Reputation: 8690

You need to change the pathMatch strategy to full in the route you are using to redirect. As per the docs,

The path-match strategy 'full' matches against the entire URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop.

Your route configuration will now look like so

export const PagesRoutes: Routes = [{
    path: '',
    children: [{
        path: '',
        redirectTo: 'courses',
        pathMatch: 'full'
    },
    // Add other routes here
    ]
}];

Upvotes: 1

Related Questions