Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular guard routes by default

Tags:

angular

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?

like image 925
jensengar Avatar asked Jan 30 '23 07:01

jensengar


1 Answers

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.

like image 138
Vitalii Chmovzh Avatar answered Feb 07 '23 17:02

Vitalii Chmovzh