5

我正在添加一个 Angular 8 路由解析器来预取数据。失败后(出于任何原因),我返回一个 EMPTY 以取消路线导航。但是,当我对此进行测试时,我可以进入 catchError 块,它显示烤面包机,并返回 EMPTY,但不会取消路线导航。根据我读过的所有文章,这应该有效。想知道是否有人看到我没有看到的东西。我只包含了 resolve 方法,因为所有其他配置都在工作。


  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Country[]> | Observable<never> {
    return this.countryService.getCountries().pipe(      
      mergeMap((countries) => {
        if (countries)
        {
          return of(countries);
        }
        return EMPTY;
      }),
      catchError(error => {
        this.toasterService.pop('error', '', 'There was a problem prefetching the data required to submit a request. If the problem persists, please notify the administrator.');
        return EMPTY;
      }));
  }

我希望此代码根据角度文档取消导航。

4

1 回答 1

2

更新:我回到源代码 angular.io 并查看了 Angular 团队如何实现解析器。他们有一段所有其他博客文章都没有的代码:

 resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Country[]> | Observable<never> {
    return this.countryService.getCountries().pipe(      
      mergeMap((countries) => {
        if (countries)
        {
          return of(countries);
        }
        this.router.navigate(['/']);//<----- THIS LINE, TO RE-DIRECT TO ANOTHER ROUTE
        return EMPTY;
      }),
      catchError(error => {
        this.toasterService.pop('error', '', 'There was a problem prefetching the data required to submit a request. If the problem persists, please notify the administrator.');
        this.router.navigate(['/']);//<----- THIS LINE, TO RE-DIRECT TO ANOTHER ROUTE
        return EMPTY;
      }));
  }

所以添加路由器重定向对我来说似乎是一个额外的步骤。特别是因为 EMPTY 会取消导航是直接矛盾的。我错过了什么?

于 2019-07-17T21:21:37.613 回答