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