interceptor/req.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class ReqInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
//请求拦截
console.log('【请求拦截】', req);
console.log('【请求拦截获取到的参数】', req.headers.get('param'));
return next.handle(req).pipe(
tap(
//响应拦截
res => {
console.log('【响应拦截】', res);
if (res instanceof HttpResponse) {
if (res.status >= 500) {
// 跳转错误页面
}
}
},
// token过期 服务器错误等处理
err => {
console.log('【服务器错误】', err);
})
);
}
}
app.module.ts
import { ReqInterceptor } from './interceptor/req.interceptor';
...
imports: [
...
HttpClientModule,//这个很重紧要,没有就会报错
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: ReqInterceptor, //自定义拦截器的类名
multi: true //这是必须的,因为它会告诉 Angular 这个 HTTP_INTERCEPTORS 表示的是一个数组,而不是单个的值。
}
],
...
services/http.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class HttpService {
private apiUrl = "http://localhost:8888/test/1.json";
constructor(private http: HttpClient) { }
public getData(params: any) {
return this.http.get(this.apiUrl, {
params,
headers: { 'param': 'get传给拦截器的参数' }
});
}
public postData(params: any) {
return this.http.post(this.apiUrl,
{ params },
{
headers: { 'param': 'post传给拦截器的参数' }
});
}
}
app.component.ts
import { HttpService } from './services/http.service';
...
constructor(
public http: HttpService
) { }
...
ngOnInit() {
this.http.getData({ param1: 1, param2: 2 }).subscribe(d => {
console.log(d);
});
this.http.postData({ param1: 1, param2: 2 }).subscribe(d => {
console.log(d);
});
}
运行起来后网页中F12打开查看
这样我们就可以根据不同的接口来源,执行针对性的拦截措施