Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 restrict all routes

Tags:

angular

Helloo,

I have created a guard:

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router) { 
    }

    canActivate() {

        if (localStorage.getItem('currentUser')) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page
        this.router.navigate(['/login']);
        return false;
    }
}

and have multiple modules with multiple routes inside them. How do I easily restrict every route in my app with this guard?

Best regards

like image 678
mp3por Avatar asked Nov 18 '16 08:11

mp3por


2 Answers

Setup an empty route with guard, and make the rest of your routes children of that one:

RouterModule.forRoot([
  { path: '', canActivate: [AuthGuard], children: [...restOfYourRoutes] }])
like image 138
Sasxa Avatar answered Oct 05 '22 17:10

Sasxa


You can use componentless routes

{ path: '', canActivate: [MyGuard], children: [
   {path: 'x1', ...},
   {path: 'x2', ...},

MyGuard will be applied to all child routes.

like image 38
Günter Zöchbauer Avatar answered Oct 05 '22 19:10

Günter Zöchbauer