在Angular 7中,可以使用HttpInterceptor来拦截API请求和响应。以下是一个示例,演示如何在数据到达之前拦截API的200状态码,并显示一个警报,然后稍后订阅/处理数据。
首先,创建一个名为ApiInterceptor的拦截器,实现HttpInterceptor接口。
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class ApiInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse && event.status === 200) {
// 显示警报
alert('API返回200状态码');
}
})
);
}
}
然后,在app.module.ts文件中,将ApiInterceptor添加到providers数组中,并将其注册为HTTP_INTERCEPTORS。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { ApiInterceptor } from './api.interceptor';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ApiInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
现在,当API返回200状态码时,将显示一个警报。
注意:你需要根据自己的需求来自定义警报的显示方式。上述示例中使用了alert()函数来显示警报,你可以根据自己的UI框架或组件来替换它。