美文网首页
angular 7.0 http Interceptor 拦截器

angular 7.0 http Interceptor 拦截器

作者: 心中翼 | 来源:发表于2019-02-21 13:38 被阅读0次

    angular的版本变动太快,写过angular1,angular4的拦截器,到了7.0的拦截器搞了好长时间,在此记录下。
    1、实现HttpInterceptor 接口

    import {Injectable} from "@angular/core";
    import {
      HttpErrorResponse,
      HttpEvent,
      HttpHandler,
      HttpInterceptor,
      HttpRequest,
      HttpResponse
    } from "@angular/common/http";
    
    import {Observable, of, throwError} from "rxjs";
    import {catchError} from "rxjs/internal/operators";
    import {Router} from "@angular/router";
    
    /** Pass untouched request through to the next request handler. */
    @Injectable()
    export class MyInterceptor  implements HttpInterceptor {
    
      constructor(private router: Router) {}
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
          catchError((err: HttpErrorResponse) => this.handleData(err))
        ) ;
      }
    
      private handleData(
        event: HttpResponse<any> | HttpErrorResponse,
      ): Observable<any> {
        // 业务处理:一些通用操作
        switch (event.status) {
          case 401:
            console.log('not login') ;
            this.router.navigate(['/']);
            return of(event) ;
            break ;
          default:
        }
        return throwError(event) ;
      }
    }
    

    2、在app.module.ts中provide

      providers: [
        { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
        ],
    

    相关文章

      网友评论

          本文标题:angular 7.0 http Interceptor 拦截器

          本文链接:https://www.haomeiwen.com/subject/chwcyqtx.html