如何修复Angular 7 Router Guard无法正常工作

时间:2019-01-07 07:51:10

标签: angular

我正在尝试编写一个路由器保护程序,以检查是否接受了页面条款,如果没有,则拒绝访问。

这是服务:

@Injectable()
export class ItemService {
  public _itemsSource = new Subject<any | null>();
  itemsObservable = this._itemsSource.asObservable();


  constructor(
    public afs: AngularFirestore
  ) {
  }

  getItemSettings(){
   return  this.itemsObservable.pipe(
      first(),
      switchMap(item => {
       return this.afs.doc(`table-items/${item.id}`).valueChanges();
      })
    );

  }

这是守卫:

@Injectable()
export class ItemEditGuard implements CanActivate {
  constructor(private itemService: ItemService, private router: Router,  private notify: NotifyService) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | boolean {
      return this.itemService.getItemSettings().pipe(
        take(1),
        map((settings: any) =>  !!settings.terms),
        tap(acceptedTerms => {
          if (!acceptedTerms) {
            this.notify.update('<strong>Access Denied!</strong> You need to accept to collection terms to continue!', 'error');
            return;
          }
      })
    );
  }
}

路由器模块

 {
      path: 'edit',
      component: ItemEditComponent,
      canActivate: [ItemEditGuard],
      data: { title: 'Edit item', breadcrumb: 'EDIT' },
}

不幸的是,这无法正常工作且未记录任何错误。 顺便说一句,它在一个延迟加载的模块上。 我究竟做错了什么?以及我该如何解决?

1 个答案:

答案 0 :(得分:0)

1_ tap() 运算符通常用于在进行订阅之前对接收的值执行某些操作,而 map 用于操纵,转换它。 / p>

2_就像您说的那样,您尝试在 lazyloaded 模块中使用此防护,因此需要实现 canLoad 接口,不是 canActive

@Injectable() export class ItemEditGuard implements CanActivate { constructor( private itemService: ItemService, private router: Router, private notify: NotifyService ) { } canActivate( route: Route, segments: UrlSegment[] ): Observable<boolean> | boolean { return this.itemService.getItemSettings() .pipe( map((settings: any) => !!settings.terms), map(acceptedTerms => { if (!acceptedTerms) { this.notify.update('<strong>Access Denied!</strong> You need to accept to collection terms to continue!', 'error'); } return acceptedTerms; }) ); } }

您可以了解更多有关: