正如标题所说:有没有办法告诉路由器取消当前的导航?
情况如下:
此方法仅在效果的异步操作请求的资源正确返回时才起作用(HTTP 200)。但是如果动作失败(比如HTTP 404),这就是问题:
有没有办法实现一个叫天真的话:this._router.cancelAllNavigationRequests()
?
答案 0 :(得分: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);
}
}