首页 文章

Angular ngrx:异步canActive Guard必须从其他地方取消

提问于
浏览
0

正如 Headers 所说:有没有办法告诉路由器取消其当前导航?

情况如下:

  • 路线保卫派遣行动 .

  • 效果根据该操作执行异步调用 .

  • 完成后,异步调用将在属性上调度存储更新操作 .

  • 守卫订阅了该 property 的选择者(比如"property$")

  • 一旦该属性$更新,警卫决定是否允许导航 .

此方法仅在效果的异步操作请求的资源正确返回时才起作用(HTTP 200) . 但是如果动作失败(比如HTTP 404),这就是问题所在:

  • 守卫赢了't approve nor reject the navigation. It'等待,直到守卫返回真或假,才能发生其他导航请求 .

有没有办法实现一个叫,天真地说: this._router.cancelAllNavigationRequests()

1 回答

  • 0

    您没有提供任何代码,因为您的案例应该无需cancelAllNavigationRequests就可以正常处理HTTP错误 . 这是我在守卫中使用的方法,它可以帮助或给你一些想法,它类似于ngex示例中的一个:在调用服务之前,这个Guard将检查分类是否已经存在而不是部分 .

    @Injectable()
    export class ClassifiedGuardService implements CanActivate, CanActivateChild {
      constructor(private store: Store<fromRoot.State>, private classifiedService: ClassifiedService, private router: Router) {
      }
    
      vendorClassifiedAlreadyLoaded(id: string): Observable<boolean> {
        return this.store.pipe(
          select(fromContext.selectAllClassifieds),
          map(entities => {
            for (let i = 0; i < entities.length; i++) {
              if (entities[i].id === id && !entities[i].partial) {
                return true;
              }
            }
            return false;
          }),
          take(1)
        );
      }
      getVendorClassifiedFromServer(id: string) {
        return this.classifiedService.getVendorsClassified({id: id}).pipe(
          map(payload => new ClassifiedAction.GetVendorsClassifiedSuccess(payload)),
          tap((action: ClassifiedAction.GetVendorsClassifiedSuccess) => this.store.dispatch(action)),
          map(payload => !!payload),
          catchError(err => {
            this.store.dispatch(new ClassifiedAction.GetVendorsClassifiedFail(err));
            this.router.navigate(['/errors/bad-request']);
            return of(false);
          })
        );
      }
    
    
      getFullClassified(id: string): Observable<boolean> {
         return this.vendorClassifiedAlreadyLoaded(id).pipe(
            switchMap(inStore => {
              if (inStore) {
                return of(inStore);
              }
              return this.getVendorClassifiedFromServer(id);
            })
          );
      }
    
      canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
        return this.getFullClassified(route.params['id']);
      }
    
      canActivateChild(route: ActivatedRouteSnapshot) {
        return this.canActivate(route);
      }
    }
    

相关问题