Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify specific request came at HTTP Interceptor using Angular 5?

I'm using HTTPInterceptor feature in Angular 5. It is working as expected while cloning http-request and sending to server(back-end server). I am showing and hiding application loader from HTTPInterceptor only and this also working fine but i have used polling on one GET request, which fetches data from back-end server in every 5 seconds which makes users irritating. So, Is there any way to check specific request in HTTPInterceptor? and also do not allow to show/hide loader on that request.

Following is the current code snippet of intercept function:

  intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.loadingIndicatorService.showLoader();
    this.customAuthorizationHeader();
    const apiRequest = req.clone({headers:this.headers});
    return next.handle(apiRequest).do
    ((response) => {
        if (response instanceof HttpResponse) {
          this.loadingIndicatorService.hideLoader();
        }
      },
      (error) => {
        this.loadingIndicatorService.hideLoader();
      });
  };

Thanks in advance.

like image 339
Chandan Avatar asked Jul 06 '18 13:07

Chandan


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 are HTTP interceptors and how do you use them 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 HTTP request interceptor?

A request interceptor is a piece of code that gets activated for every single HTTP request received by your application. Interceptors are very useful when you need to perform some common processing for every HTTP request.

How many types of interceptors are there in angular?

In this post, we cover three different Interceptor implementations: Handling HTTP Headers. HTTP Response Formatting. HTTP Error Handling.


1 Answers

You can check the if the req.url is equal to the path you want to exclude like below:

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // put this before your current code
    if (req.url.indexOf('/* the api path you want to exclude*/') === -1) {
      return next.handle(req);
    }
    // do your stuff here.
    return next.handle(req);
  }
like image 99
Envil Avatar answered Oct 25 '22 04:10

Envil