2

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

情况如下:

  • 路由守卫分派一个动作。
  • 效果基于该操作执行异步调用。
  • 完成后,异步调用将在属性上调度存储更新操作。
  • 守卫订阅了该属性的选择器(比如“property$”)
  • 一旦该属性 $ 更新,守卫决定是否允许导航。

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

  • 守卫不会批准也不会拒绝导航。它处于未决状态,并且在守卫返回 true 或 false 之前不会发生其他导航请求。

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

4

1 回答 1

1

您没有提供任何代码,因为您的案例应该可以在不需要 cancelAllNavigationRequests 的情况下工作,您只是没有正确处理 HTTP 错误。这是我在警卫中使用的一种方法,它可能会帮助或给你一些想法,它类似于 ngex 示例中的方法:这个警卫将在调用服务之前检查分类是否已经存在并且不是部分的。

@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);
  }
}
于 2018-03-17T11:19:19.557 回答