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

Problem with HttpInterceptor in Angular 8 - HTTPInterceptor is not triggered

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

MyInterceptorService Class 代码:

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 ')
      })
    );

  }
}

模块Class代码

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 Header 未更新

您确定在代码中的某处发出了 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