美文网首页我爱编程
Angular 2+ 路由守卫

Angular 2+ 路由守卫

作者: 环零弦 | 来源:发表于2018-04-19 17:51 被阅读0次

    具体逻辑比较简单,就是看要触发的路由是不是在 LocalStorage 里存着。

    import { Injectable } from '@angular/core';
    import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from '@angular/router';
    import { LocalStorageService } from './local.storage.service';
    import { Observable } from 'rxjs/Observable';
    
    @Injectable()
    export class CanAuthProvide implements CanActivate {
      private privilegeFrontSet: Set<string>;
    
      constructor(private ls: LocalStorageService) {
        this.privilegeFrontSet = new Set(JSON.parse(this.ls.get('privilegeFront')) || []);
      }
    
      check(route: ActivatedRouteSnapshot): Observable<boolean> {
        return new Observable((observer) => {
          if (!this.privilegeFrontSet.has(route.routeConfig.path)) {
            // TODO 逻辑相反
            observer.next(true);
            observer.complete();
            return;
          }
          observer.next(false);
          observer.complete();
        });
      }
    
      canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
        return this.check(route);
      }
    }
    

    参考资料:

    相关文章

      网友评论

        本文标题:Angular 2+ 路由守卫

        本文链接:https://www.haomeiwen.com/subject/ortgkftx.html