1

I need your help to implements my 404 component for child route with id, without redirection to a "404" page. This child route has a resolver that fetches my API. When the API return a 404, I want to redirect to show my 404 component but without redirection.
Here's my code:

routing.module.ts

 const route = [
 ...
  {
    path: ':id',
    component: ChildComponent,
    resolve: {
      data: ChildResolver,
    },
  },
  {
    path: '**',
    pathMatch: 'full',
    component: ErrorPageComponent,
  },
...

child resolver

...
  public resolve(route: ActivatedRouteSnapshot): Observable<ChildItem> {
    return this.fetch(route.params.id);
  }
...

NB: ErrorPageComponent is a dumb component who just displays the error message. Ps: Sorry for my English, I'm French.

Thanks a lot, Best regards William

1 Answers1

0

There can be two ways of doing this:

  1. If you get an error from the API, you can create custom message based on that ex: 404 - 'Page Not Found'.

  2. You can redirect to the global error handler with a custom message which you don't need, but can be an option to consider.

If you get an error from the API, you can create custom message based on that ex: 404 - 'Page Not Found'.

import { catchError } from 'rxjs/operators';
...
...
 public resolve(route: ActivatedRouteSnapshot): Observable<ChildItem> {
    this.fetch(route.params.id).pipe(catchError((err) => {
      return of(err);
    }));
  }

In the child component, based on the received error message/code enable the ErrorPageComponent in the child component using ngIf.

You must be checking the status codes received from the response if not you can implement that using this link.

You can redirect to the global error handler with a custom message which you don't need, but can be an option to consider.

import { Observable, EMPTY } from 'rxjs';
import { catchError } from 'rxjs/operators';
...
...
 public resolve(route: ActivatedRouteSnapshot): Observable<ChildItem> {
    this.fetch(route.params.id).pipe(catchError((err) => {
      if (err.status === 404) this.route.navigate['/ERRORPAGECOMPONENT'] 
      return EMPTY
    }));
  }

You can check here for how to handle errors in resolve.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35