Interceptor not intercepting http requests (Angular 6)

前端 未结 5 857
自闭症患者
自闭症患者 2021-01-01 11:10

I\'m in the proces of adding an interceptor to my angular 6 project. To make calls to my API, I need to add a bearer token to all calls. Unfortunately the interceptor does n

5条回答
  •  梦毁少年i
    2021-01-01 11:58

    You use the right way to intercept.

    For people who use interceptor, you need to do 2 modifications :

    Interceptor in service

    import { Injectable } from '@angular/core';
    import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse }
      from '@angular/common/http';
    
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/do';
    
    @Injectable()
    export class MyInterceptor implements HttpInterceptor {
      intercept(
        req: HttpRequest,
        next: HttpHandler
      ): Observable> {
    
        return next.handle(req).do(evt => {
          if (evt instanceof HttpResponse) {
            console.log('---> status:', evt.status);
            console.log('---> filter:', req.params.get('filter'));
          }
        });
    
      }
    }
    

    Provide HTTP_INTERCEPTOR

    import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
    (...)
      providers: [
        { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
      ],
    

    Read this article for more details. It's pretty good

提交回复
热议问题