HttpInterceptor不拦截

时间:2019-06-27 20:05:39

标签: angular angular-http-interceptors

我正在尝试实现http-Interceptor,但实际上它不起作用,我也不明白为什么。代码如下,首先进行一些解释:

服务中的http.get无处可去(因此应该出现错误或?这是我要使用Interceptor进行的:记录生产错误。)

我以为算法尝试发送请求,然后拦截器跳入管道,然后点击和/或(?)终结函数处于活动状态,我在控制台上看到了一些东西。但是什么也没发生。

拦截器:

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

1 个答案:

答案 0 :(得分:1)

您需要使用TestService getUsers()方法调用subscribe。否则将无法拨打电话。

更改此行:

this.test.getUsers();

对此:

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

检查文档here