flyboy78
flyboy78

Reputation: 81

Angular 8 route resolver not canceling route navigation when return EMPTY

I'm adding an Angular 8 route resolver to prefetch data. Upon failure (for any reason) I return an EMPTY to cancel the route navigation. However, when I test this, I can step into the catchError block, it shows the toaster, and it returns EMPTY, but the route navigation is not being canceled. According to all the articles I have read, this should work. Wanted to know if anybody sees something that I don't. I have only included the resolve method, since all other configuration is working.


  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;
      }));
  }

I expect this code to cancel navigation, per angular documentation.

Upvotes: 5

Views: 4320

Answers (1)

flyboy78
flyboy78

Reputation: 81

Update: I went back to the source, angular.io and looked at how the angular team implemented the resolver. They had a piece of code that all other blog posts were missing:

 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;
      }));
  }

So adding the router re-direct seems like an extra step to me. Especially since it is in direct contradiction that the EMPTY would cancel the navigation. What am I missing?

Upvotes: 2

Related Questions