HttpInterceptor 不拦截

HttpInterceptor does not intercept

我正在尝试实现一个 http 拦截器,但实际上它不起作用,我不明白为什么。代码如下,先稍微解释一下:

服务中的http.get无处可去(所以应该有错误还是?这就是我想使用拦截器的目的:记录生产错误。)

我认为算法尝试发送请求,然后拦截器跳入、管道然后点击 and/or(?) finalize 处于活动状态,我在控制台上看到了一些东西。但是没有任何反应。

拦截器:

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap, finalize } from 'rxjs/operators';

export class HttpErrorInterceptor implements HttpInterceptor{
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log("INTERCEPT");
        return next.handle(req).pipe(
            tap(ev => {
                console.log("TAP");
            }),
            finalize(() => {
                console.log("FINALIZE");
            })

        );
    }
}

app.module.ts

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

import { AppComponent } from './app.component';
import { HttpErrorInterceptor } from './http-error.interceptor';
import { HTTP_INTERCEPTORS, HttpClientModule  } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule 
  ],
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: HttpErrorInterceptor,
    multi: true
  }],
  bootstrap: [AppComponent]
})
export class AppModule { }

test.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class TestService {


  private apiUrl = 'https://localhost:8080/api/users';

  constructor(private http: HttpClient) { }

  getUsers(): Observable<String[]> {
    return this.http.get<String[]>(this.apiUrl)
  }
}

和app.component.ts

import { Component } from '@angular/core';
import { TestService } from './test.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'errorHandling';

  constructor(private test: TestService){}

  ngOnInit(){
    console.log("INIT");
    this.test.getUsers();
  }
}

您需要在 TestService getUsers() 方法上调用订阅。否则将不会进行调用。

更改此行:

this.test.getUsers();

为此:

this.test.getUsers().subscribe();

检查文档 here