Angular 8中的HttpInterceptor问题-未触发HTTPInterceptor

时间:2019-12-05 12:02:27

标签: angular8 angular-http-interceptors request-headers

我有一个简单的HttpInterceptor代码,我试图在请求标头中添加一些数据,但这不起作用。

MyInterceptorService类代码:

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

@Injectable()
export class MyInterceptorService implements HttpInterceptor {

  constructor() { }

  intercept(req:HttpRequest<any>, next:HttpHandler):Observable<HttpEvent<any>>
  {
    console.log("hello");
    return next.handle(
      req.clone({
        headers: req.headers.set('Authorization', 'Bearer ')
      })
    );

  }
}

模块类代码

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {FormsModule} from '@angular/forms';
import { SecretComponent } from './secret/secret.component';
import { ErreurComponent } from './erreur/erreur.component';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyInterceptorService } from './my-interceptor.service';
@NgModule({
  declarations: [
    AppComponent,
    SecretComponent,
    ErreurComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MyInterceptorService,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

从不显示控制台消息,并且不更新Http标头

1 个答案:

答案 0 :(得分:0)

确定要在代码中的某个地方进行HTTP请求吗?例如:

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

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

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get('http://www.google.com')
      .subscribe();
  }
}

我通过复制粘贴MyInterceptorService创建了一个Stackblitz示例,它显示了控制台“ hello”消息:https://stackblitz.com/edit/angular-rhpnjg