Angular路由拦截

对于未登入的用户,无法访问其他模块,当点击其他功能模块时跳转到登入界面

在app-routing.modle.js中加入拦截

const routes: Routes = [
  {
    path: '**', component: ***,
    canActivate: [LoginGuard]
  }
 ]

具体拦截功能实现

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { LocalStorage } from '../common/local.storage';

@Injectable()
export class LoginGuard implements CanActivate {
    constructor(private router: Router, private store: LocalStorage) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let isLogin: boolean;
        // 判断用户是否登入
        const user = this.store.getObject('user');
        if (JSON.stringify(user) === '{}') {
            isLogin = false;
            // 未登入跳转到登入界面
            this.router.navigateByUrl('/login');
        } else {
            isLogin = true;
        }
        return isLogin;
    }
}

你可能感兴趣的:(Angular路由拦截)