简体   繁体   English

拦截器不拦截 http 请求(Angular 6)

[英]Interceptor not intercepting http requests (Angular 6)

I'm in the proces of adding an interceptor to my angular 6 project.我正在为我的 Angular 6 项目添加一个拦截器。 To make calls to my API, I need to add a bearer token to all calls.要调用我的 API,我需要为所有调用添加一个不记名令牌。 Unfortunately the interceptor does not seem to be called.不幸的是,拦截器似乎没有被调用。 My code:我的代码:

import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Observable } from "rxjs";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

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

        //Retrieve accesstoken from local storage
        const accessToken = localStorage.getItem("access_token");

        //Check if accesToken exists, else send request without bearer token
        if (accessToken) {
            const cloned = req.clone({
                headers: req.headers.set("Authorization",
                    "Bearer " + accessToken)
            });

            console.log('Token added to HTTP request');

            return next.handle(cloned);
        }
        else {
            //No token; proceed request without bearer token
            console.log('No token added to HTTP request');
            return next.handle(req);
        }
    }
}

Does anyone know what could be causing this issue?有谁知道可能导致此问题的原因是什么? Thanks in advance.提前致谢。

In my case interceptor wasn't getting involved for service calls because I had imported HttpClientModule multiple times, for different modules.在我的情况下,拦截器没有参与服务调用,因为我为不同的模块多次导入了HttpClientModule

Later I found that HttpClientModule must be imported only once.后来发现HttpClientModule只能导入一次。 Doc ref文件参考

Hope this helps!希望这可以帮助!

You use the right way to intercept.你用正确的方式拦截。

For people who use interceptor, you need to do 2 modifications :对于使用拦截器的人,您需要进行 2 处修改:

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<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {

    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提供 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这个很不错

If you have a providers array for a module then you have to define the HTTP_INTERCEPTORS too for that module then only it will intercept the requests under that module.如果您有一个模块的 providers 数组,那么您必须为该模块定义 HTTP_INTERCEPTORS ,那么只有它会拦截该模块下的请求。

eg:例如:

providers: [ 
// singleton services
PasswordVerifyService,
{ provide: HTTP_INTERCEPTORS, useClass: AppInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptorService, multi: true }
]

就我而言,我必须在同一个模块中同时导入HTTP_INTERCEPTORS, HttpClientModule

In my case i had a post method like this:就我而言,我有一个这样的 post 方法:

this.http.post<any>(this.authUrl, JSON.stringify({username: username, password: password})).pipe(
      map((response: any) => {
            let token: any = response.token;
            if (token) {
                localStorage.setItem('currentUser', 'value' }));                
                return response; 
            } else {
                return null;
            }
        }),
        catchError((error:any) => {return observableThrowError(error.json().error || 'Server error')})
      );

Because the map method could return null the interceptor stopped intercepting the requests made with this post method call.因为map方法可能返回null ,所以拦截器停止拦截使用此 post 方法调用发出的请求。 Don't ask me why this is so, but as soon as i replace null with say response everything started working again.不要问我为什么会这样,但是一旦我用说response替换null ,一切又开始工作了。

就我而言,我不知道如何,但我使用的是useValue而不是useClass

在我的情况下,我不小心在我的组件中提供了服务providers : [ ApplicationService ] ,而它不应该像我使用providedIn: 'root'定义的那样

Please ensure that dependencies for the interceptor are also provided in the module.请确保模块中还提供了拦截器的依赖项。 ProvidedIn:'root' for the interceptor dependency services did not work for me.拦截器依赖服务的 ProvidedIn:'root' 对我不起作用。

In my case, since I am working with modules, I had to import the child module (AuthModule) in app.module.ts .就我而言,由于我正在使用模块,因此我必须在app.module.ts中导入子模块(AuthModule) I was just missing that.我只是想念那个。

imports: [ HttpClientModule, AppRoutingModule, AuthModule ]进口:[HttpClientModule,AppRoutingModule,AuthModule]

检查您的模块和子模块文件,如果您已在子模块中导入拦截器,则将其移动到根模块,它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM