0

In Angular 6 I'm using an observable to manage fetching a detail record based on the URL parameter like so:

ngOnInit() {
  this.hero$ = this.route.paramMap.pipe(
    switchMap((params: ParamMap) => {
      const id = parseInt(params.get('id'), 10);
      if (!id) {
        throw new Error('Hero id invalid.');
      }
      return this.service.getHeroById(id);
    }),
    catchError(err => {
      this.router.navigate(['/pageNotFound'], {skipLocationChange: true});
      return throwError(err);
    }),
  );
}

In the catchError pipe I'm just navigating to a URL that doesn't exist which causes the wildcard route to trigger and display my PageNotFoundComponent. That seems really convoluted, but I don't understand how else to cause the router to display that component. Is there a better way?

This is a demo of my setup: https://stackblitz.com/edit/angular-router-not-found?file=src%2Fapp%2Fhero%2Fhero-detail.component.ts

Rob
  • 3,687
  • 2
  • 32
  • 40
  • Maybe you could leverage `canActivate` on the route? If that returns false and no other route matches, it should go to your wildcard route – Vlad274 Sep 20 '18 at 21:12
  • could you make your stackblitz to run the application not test ? btw your page is not registred in the router so actually it give us few information – xrobert35 Sep 20 '18 at 21:20
  • Futhermore I nearly agree with @Vlad274 except that for me this is the purpose of the **resolver** to resolve data, and if the data can't be resolve it should redirect to the PageNotFoundComponent – xrobert35 Sep 20 '18 at 21:24
  • maybe instead of using the wildcard to route to a component, use the wildcard to redirect to another route? something like {path: '**',redirectTo: '404'} – Jota.Toledo Sep 20 '18 at 21:29
  • For me the /pageNotFound route should really exist in the router. Normally you try to use wildcard route to redirect the user to a friendly page. The home page for exemple or a list of data based on the nearest route – xrobert35 Sep 20 '18 at 21:36
  • I updated the stackblitz to run the app instead of the tests. – Rob Sep 20 '18 at 22:01
  • @Vlad274 Not sure how that would work, got an example of that I can check out? This is what I found, but not sure why this is better. https://www.concretepage.com/angular-2/angular-resolve-guard-example – Rob Sep 21 '18 at 15:05

0 Answers0