Search code examples
angular6angular-http-interceptors

Angular 6 Interceptor not working as expected


I have written an Http Interceptor in Angular 6 . The goal is to reload the home page when 302 status is returned. (any back end API returning 302 status ) I am currently not able to understand why the Interceptor is behaving the way it is.

Below is the code :

@Injectable()
export class ResponseHandler implements HttpInterceptor{


    constructor(){

    }

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


     return next.handle(request).pipe(


            map((event: HttpEvent<any>) => {

                if(event instanceof HttpResponse){
                    if(event.status === 302){
                        console.log('HttpResponse 302 status ');
                        window.location.reload();
                        return EMPTY;
                    }
                }

            })
        )

    }

}

Actual Behaviour :

1)I am first accessing the home page explicitly. (e.g: /home)

2)But the strange thing is , the initial call to fetch home age itself is not happening

3)It seems request is blocked reaching the server.

4)When interceptor is removed , this initial call is happening (/home)

I am not able to understand why is this behaviour ?

Why the request is getting blocked as I am NOT tampering with request it should be passed as is to back end rest end point .

It should be intercepted only when HttpResponse is returned with 302 error code .

Can anybody please help here ?


Solution

  • The problem is that you forgot to return value in map operator. The main goal of map operator is to modify data and RETURN it back.

             map((event: HttpEvent<any>) => {
    
                if(event instanceof HttpResponse){
                    if(event.status === 302){
                        console.log('HttpResponse 302 status ');
                        window.location.reload();
                        return EMPTY;
                    }
                }
    
                return event;  // here you return value back
            })