ionic3 + angular5 添加http请求拦截器

注:此拦截器只能拦截HttpClient,不能拦截Http

1、创建拦截器


ng g provider interceptor

2、修改拦截器内容
 

import {
  HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse
} from "@angular/common/http";
import {Injectable} from "@angular/core";
import {catchError, tap} from "rxjs/operators";
import {Observable} from "rxjs";
import {ToastController, LoadingController} from "ionic-angular";

@Injectable()
export class InterceptorProvider implements HttpInterceptor {

  private timeoutMillis = 3000;

  constructor(
    private toastCtrl: ToastController,
    private loadingCtrl: LoadingController
  ) {
  }

  intercept(
    request: HttpRequest,
    next: HttpHandler
  ): Observable> {
    console.log('终于拦截到了。。。', request.url);
    /**
     * 请求前置处理
     */
    let loadingView = this.loadingCtrl.create({
      spinner: "hide",
      content: ``,
      dismissOnPageChange: false
    });

    loadingView.present();
    let token = window.localStorage.getItem("token");
    const authRequest = request.clone({
      headers: request.headers.set("Authorization", "Bearer " + token)
    });

    return next
      .handle(authRequest)
      .timeout(this.timeoutMillis)
      .pipe(
        tap(
          event => {
            if (event instanceof HttpResponse) {
              /**
               * 请求后置处理
               */
              loadingView.dismiss();
            }
          },
          error => {
            /**
             * 请求异常处理
             */
            loadingView.dismiss();
            let msg = "请求失败";
            switch (error.status) {
              case 0:
                msg = "请求地址错误";
                break;
              case 400:
                msg = "请求无效,请检查参数类型是否匹配";
                break;
              case 404:
                msg = "请求资源不存在,请检查路径是否正确";
                break;
              default:
                break;
            }
          }
        ),
        catchError((err: any) => {
          return Observable.throw(err.message);
        })
      );
  }
}

3、将拦截器添加到app.module.ts

@NgModule({
  imports: [
    HttpClientModule, HttpModule,
  ],
  providers: [
    ...
    {provide:HTTP_INTERCEPTORS,useClass:InterceptorProvider,multi:true},
    ...
  ]
})
export class AppModule {
}

 

你可能感兴趣的:(JavaWeb,angular)