Angular-无法使用http服务拦截HTTP请求

时间:2018-07-25 20:22:37

标签: angular

我有一个角度为6的应用程序。

我正在将HTTP拦截器分配给特定的延迟加载模块。当我使用http客户端直接在组件中进行http调用时,请求将被拦截。但是,通过核心模块服务进行http调用,将无法拦截这些http请求。

请参见以下示例。

https://stackblitz.com/edit/angular-ckzdvx?file=src%2Fapp%2Fa%2Ffirst%2Ffirst.component.ts

first.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ApiService } from './../../core/api.service';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {

  constructor(private http: HttpClient, private apiService: ApiService) { }

  ngOnInit() {
  }

  call() {
    this.http.get("https://jsonplaceholder.typicode.com/users").subscribe((res) => {
      console.log(res);
    })
  }

  call2() {

    this.apiService.get("https://jsonplaceholder.typicode.com/users").subscribe((res) => {
      console.log(res);

    });

  }

}

用例

我正在打2个电话,第一个call()被截获,第二个call2()没有被截获。

结果

call2()在使用api服务时应被拦截。

重要的是,仅在需要的模块中声明http拦截器。因为我不希望其他模块拦截其HTTP请求。

3 个答案:

答案 0 :(得分:2)

我不知道是否有可能开箱即用地做您所需要的事情,但是当我遇到类似的问题(必须拦截除一个服务之外的所有服务/模块的调用)时,我编写了拦截器来检查请求标头并做出反应对此。我在“无拦截请求”中添加了特殊的标头“ skip-app-id”,以触发拦截器本身中的请求拦截绕过

因此,基本上,如果请求包含“ trigger”标头,拦截器将跳过拦截。您可以执行类似的方法,并在拦截的请求中添加特殊的控制头以触发拦截,否则将其绕开。

将其包装起来,通常是这样的:

  1. 提供全局拦截器(因为这是最简单的方法,您已经知道了)
  2. 使其标头敏感-拦截器必须检查请求标头
  3. 如果请求包含指定的标头-可以说“ do-intercept:true”来执行拦截工作
  4. 从请求中删除“ do-intercept:true”标头,因为我们不想将其发送到任何地方
  5. 如果没有触发头,则跳过拦截逻辑(短路)

或多或少可以完全满足您的要求。

答案 1 :(得分:-1)

我认为您需要将以下提供程序添加到app.module.ts中才能满足所有请求

import { HttpClientModule, HTTP_INTERCEPTORS } from 
'@angular/common/http';

import { MyInterceptor} from './my.interceptor';

@NgModule({
 imports: [BrowserModule, FormsModule, AppRoutingModule,
 CoreModule.forRoot(),
 HttpClientModule],
 declarations: [AppComponent],
 bootstrap: [AppComponent],
 providers: [
 {
  provide: HTTP_INTERCEPTORS,
  useClass: MyInterceptor,
  multi: true
 }
 })
 export class AppModule { }

答案 2 :(得分:-1)

call2()未命中拦截器的原因是:它未使用FirstComponent注入的HttpClient。它改用ApiServiceApiService的实例在构造函数中注入了自己的HttpClient,并且 HttpClient没有提供MyInterceptor作为HTTP_INTERCEPTOR

更改对this.http.get的第二次调用将使其打中您的拦截器。