Angular2限制所有路线 [英] Angular2 restrict all routes

查看:40
本文介绍了Angular2限制所有路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
    }
}

,并具有多个内部带有多个路由的模块.如何使用此后卫轻松限制应用程序中的每条路线?

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

最诚挚的问候

推荐答案

设置带有防护的空路由,并将其余路由设为该路由的其余部分:

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

RouterModule.forRoot([
  { path: '', canActivate: [AuthGuard], children: [...restOfYourRoutes] }])

这篇关于Angular2限制所有路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆