Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular4 Interceptor change response

I have an auth HttpInterceptor:

import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, 
HttpRequest} from '@angular/common/http';
import {AuthService} from '../service/auth.service';
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService,
              private router: Router) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authHeader = this.authService.getToken();
    const clone = req.clone({headers: req.headers.set('Authorization',authHeader)});
    return next.handle(clone).do(() => {
}, err => {
  console.log(err);
  if (err instanceof HttpErrorResponse && err.status === 401) {
    this.authService.clearToken();
    this.router.navigate(['/auth/signin']);
    return Observable.empty();
      }
    });
  }
}

This interceptor works fine, but when i'm getting 401 i'm redirecting user to login page, but the error still goes to the service, and in that service i'm showing error msg, and this msg showing at signin page. So i want to change response or do something in if (err instanceof HttpErrorResponse && err.status === 401) { block, to not returning error in this case.

return Observable.empty();

is not working

like image 523
user2870934 Avatar asked Sep 20 '17 19:09

user2870934


People also ask

Can angular have multiple HTTP interceptors?

After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.

What is HttpInterceptor in angular?

HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response. Keep in mind that the interceptor wants only HTTP requests.

What is HttpHandler in angular?

Descriptionlink. HttpHandler is injectable. When injected, the handler instance dispatches requests to the first interceptor in the chain, which dispatches to the second, etc, eventually reaching the HttpBackend . In an HttpInterceptor , the HttpHandler parameter is the next interceptor in the chain.

What is Http_interceptors?

HTTP_INTERCEPTORSlinkA multi-provider token that represents the array of registered HttpInterceptor objects.


1 Answers

next.handle(clone).do() - this is what's causing such behavior. do() operator is intended only to provide side-effects, but it does not actually affect data flow and error handling in the observable pipe. Essentially it is saying "when this happens please do this and that and then continue as if there's no do() section at all". If you want to suppress errors then you need to use catch() operator.

Code would be almost the same:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private authService: AuthService,
                private router: Router) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authHeader = this.authService.getToken();
        const clone = req.clone({headers: req.headers.set('Authorization',authHeader)});
        return next.handle(clone).catch(err => { // <-- here
            console.log(err);
            if (err instanceof HttpErrorResponse && err.status === 401) {
                this.authService.clearToken();
                this.router.navigate(['/auth/signin']);
                return Observable.empty();
            }
            // we must tell Rx what to do in this case too
            return Observable.throw(err);
        });
    }
}
like image 122
Alexander Leonov Avatar answered Sep 25 '22 03:09

Alexander Leonov