angular5 HttpInterceptor使用

HttpInterceptor接口是ng的http请求拦截器,当需要拦截http请求,可以实现该接口。

1.创建HttpInterceptor 的实现类,并使用@Injectable()注解

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {

    constructor(private injector: Injector) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            mergeMap((event: any) => {
                // if (event instanceof  HttpResponse) {
                // }
                return of(event);
            }),
            catchError((err: any) => {
                // 错误处理
                return ErrorObservable.create(event);
            })
        );
    }
}

2.在app.module中配置

如下所示:

@NgModule({
    providers: [
        { provide: HTTP_INTERCEPTORS, useClass: MyHttpInterceptor , multi: true}
    ]
})

其中,multi: true表示可以使用相同的Token去注册多个Provider,也就是可以注册多个HttpInterceptor 的实现类