Angular 2+ 路由守卫

具体逻辑比较简单,就是看要触发的路由是不是在 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;

  constructor(private ls: LocalStorageService) {
    this.privilegeFrontSet = new Set(JSON.parse(this.ls.get('privilegeFront')) || []);
  }

  check(route: ActivatedRouteSnapshot): Observable {
    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 | Promise {
    return this.check(route);
  }
}

参考资料:

  • Angular路由守卫
  • Angular4 路由守卫
  • angular路由守卫

你可能感兴趣的:(Angular 2+ 路由守卫)