Angular2限制所有路线

mp3*_*por 7 angular

Helloo,

我创造了一个警卫:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

并且有多个模块,里面有多个路由.如何使用这个警卫轻松限制我的应用程序中的每条路线?

最好的祝福

Sas*_*sxa 11

用守卫设置一条空路线,然后制作children那条路线的其余路线:

RouterModule.forRoot([
  { path: '', canActivate: [AuthGuard], children: [...restOfYourRoutes] }])
Run Code Online (Sandbox Code Playgroud)


Gün*_*uer 6

您可以使用无组件路由

{ path: '', canActivate: [MyGuard], children: [
   {path: 'x1', ...},
   {path: 'x2', ...},
Run Code Online (Sandbox Code Playgroud)

MyGuard 将适用于所有儿童路线.