Angular路由拦截

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013817676/article/details/81346965

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

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

猜你喜欢

转载自blog.csdn.net/u013817676/article/details/81346965
今日推荐