Alert and Navigate from HTTP Interceptor


#1

I created an HTTP Interceptor to catch all HTTP errors (especially 401 and 403) based on this https://blog.tomasandtomas.com/angular-2-http-interceptors-7e2d74b7f14e#.u3r61t851. Now what I want to do is alert the user when there is an error and forward to the login page when they are logged out. How can I accomplish this in a service? Do I have to pass the NavController and AlertController every time I call the service?

Thank you


#2

What I would do is have the app component subscribe to an Observable exposed from your interceptor that fires events when things have gone sideways. In its subscription listener, it can call setRoot().


#3

The application makes between 20 -30 different HTTP calls on different pages. The point of the interceptor is to trap authentication exceptions in 1 place and forward to the login page. Otherwise if I have to catch the error every time I call HTTP, I could just use the the standard HTTP class

I’m assuming you mean something like this:

this.callsService.someHttpCall(param).map(res => res.json()).catch((error) => handleError(error);

 handleError (error: any) {

    if(error.status === 403 || error.status === 401){
        nav.setRoot(LoginPage);
    }
   let errMsg = (error.message) ? error.message :
   error.status ? `${error.status} - ${error.statusText}` : 'Server error';
   return Observable.throw(errMsg);
}

If this is not what you had in mind, please expand on your reply.


#4

No, I mean something like this:

###HttpInterceptor

errors: Subject<Response>;
get(url): Observable<Response> {
  let req = this._http.get(url);
  req.subscribe((rsp) => {
  }, (err) => {
    this.errors.next(err);
  });
  return req;
}

###AppComponent

constructor(nav:NavController, http:HttpInterceptor) {
  http.errors.subscribe((err) => {
    nav.setRoot(LoginPage);
  });
}

Obviously that’s a bare skeleton, but hopefully the idea is clear.


#5

@javasol, I’m also having the same problem, you managed to make it work, if so, could you tell us how?


#6

@fndmiranda I used @rapropos idea. This works some times but I still find that there are plenty of request that get an error response or timeout and the app just hangs with no error message. It’s really frustrating