1

I am trying to call an API in canLoad event for a module in my angular application,

Even though that API is not available and gives 404 in network, still my page is loading. I wanted to avoid that situation if there is 404 then I wanted to redirect my page to some error page.

canLoad(route: Route, segments: UrlSegment[]) 
{
       return this.http.get('testapi/getacces').pipe(map((response: boolean) => {
           if (response) {
               return true;
           } else {
               this.router.navigate(['/error']);
               return false;
           }
       }));
   }

Here If API presents then my code is working as expected but the issue is only when there is 404. So, I am expecting a block which can handle the exception to route to an error page on 404 exception.

vinod j
  • 83
  • 1
  • 12

1 Answers1

0

Try using catchError() operator which will handle your situation when error arrives instead of correct response.

See example:

  canLoad(route: Route, segments: UrlSegment[]) {
    return this.http.get('testapi/getacces').pipe(
      map((response: boolean) => {
        if (response) {
          return true;
        } else {
          this.router.navigate(['/error']);
          return false;
        }
      }),
      catchError((error) =>
        of(error).pipe(
          map(() => {
            this.router.navigate(['/error']);
            return false;
          }),
        ),
      ),
    );
  }

This is useful because 404 is Error response, which will not arive inside map, but will arrive inside catchError, so you can handle Error response as you wish.

Goga Koreli
  • 2,807
  • 1
  • 12
  • 31