zoukankan      html  css  js  c++  java
  • 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 的实现类

  • 相关阅读:
    冲刺成果演示
    c#输入串字符不符
    课堂测试—数据清洗
    mapreduce实验
    问题纠错
    软件需求阅读笔记第一篇
    暑假第五周总结
    暑假第四周总结
    暑假第三周总结
    暑假第二周总结
  • 原文地址:https://www.cnblogs.com/jecyhw/p/8720047.html
Copyright © 2011-2022 走看看