jensengar
jensengar

Reputation: 6167

Angular guard routes by default

I have an app where most of my routes need to be guarded (logged in). Is it possible to add a default route guard and "whitelist" routes that should be open?

Upvotes: 5

Views: 3933

Answers (1)

Vitalii Chmovzh
Vitalii Chmovzh

Reputation: 2943

What I usually do is create a parent route for authorized part of the app with route guard on it. In fact this route has just basic component with <router-outlet></router-outlet> inside it's template, but child routes will not be accessible before hitting route guard on that route. See my example below.

const routes: Routes = [
    { path: '',  redirectTo: 'app/books', pathMatch: 'full' },
    { path: 'app', component: MainComponent, canActivate: [AuthGuard], children: [
        {path: 'books', component: BooksComponent },
        {path: 'cars', component: CarsComponent },
        {path: 'trees', component: TreesComponent }
    ]},
    { path: 'login', component: LoginComponent, canActivate: [NonauthGuard] }
];

NonAuthGuard in my case provides opposite behavior and doesn't allow user to hit login route while being authorized.

Upvotes: 9

Related Questions