快捷键
ng-http-interceptor
请求拦截
interceptors/param.interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class ParamInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const modifiedReq = req.clone({
setParams: { icode: environment.icode }
})
return next.handle(modifiedReq);
}
}
在模块中提供
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'
import { ParamInterceptor } from './interceptors/param.interceptor';
@NgModule({
...
providers: [
...
{
provide: HTTP_INTERCEPTORS,
useValue: ParamInterceptor,
multi: true,
}
]
})
响应拦截
interceptors/notification.interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpClient, HttpResponse
} from '@angular/common/http';
import { tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class NotificationInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
return next.handle(req).pipe(
tap((event: HttpEvent<any>) => {
if(event instanceof HttpResponse
&& event.status >= 200
&& event.status < 300
) {
console.log('截取成功')
}
})
)
}
}