cnak2
cnak2

Reputation: 1841

Not detecting a 404 in Angular

I have an Angular app where I'm trying to redirect to a page if my API returns a 404 status code. I'm trying to capture the error in the following way and then if it is a 404, push to another page.

  ngOnInit(){
    this.auth.memberInfo()
      .subscribe(res =>{
        this.user = res.json();
        console.log('The User: ', res.json());
        this.profileService.getProfile(res.json().id)
          .subscribe(res => {

            if(res.status === 404){
              this.navCtrl.push('CreateProfilePage');
            } else {
              this.profile = res.json();

              if(this.profile.first_name && this.profile.last_name)
                this.profileInitials = this.profile.first_name.charAt(0) + this.profile.last_name.charAt(0);
            }

          })

      })
  }

For some reason, this check isn't working and I'm not handling the error.

Can anyone see what I might be doing wrong?

Upvotes: 0

Views: 1284

Answers (1)

Vitalii Chmovzh
Vitalii Chmovzh

Reputation: 2943

The most efficient way to do that is to use interceptors. Simply declare your interceptor like that:

not-found.interceptor.ts

import {Injectable} from '@angular/core';
import {
  HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest
} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {Router} from '@angular/router';
import 'rxjs/add/operator/catch';
import {ErrorObservable} from 'rxjs/observable/ErrorObservable';

@Injectable()
export class NotFoundInterceptor implements HttpInterceptor {
  constructor(private router: Router) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(req)
      .catch((response: HttpErrorResponse) => {
        if (response.status === 404) {
          this.router.navigate('/your-404-route');
        }

        return ErrorObservable.create(response);
      });
  }
}

Then provide it in app.module.ts:

providers: [
...
    {
      provide: HTTP_INTERCEPTORS,
      useClass: NotFoundInterceptor,
      multi: true
    }
...
  ],

Now for any HTTP call you send, if you'll get 404 back it will redirect user to your 404 page. You can use this approach for many things, like:

  1. Unauthorize user on 401 response
  2. Forbidden page
  3. Global error handling
  4. You name it :)

Upvotes: 1

Related Questions