angular4 httpclient拦截器

1.创建服务:

InterceptorService.ts

  

import { Injectable } from '@angular/core';
import { HttpEvent,HttpInterceptor,HttpHandler,HttpRequest,HttpResponse} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { catchError } from 'rxjs/operators';
import { mergeMap } from 'rxjs/operators';
@Injectable()
export class InterceptorService implements HttpInterceptor{

  intercept(req:HttpRequest,next:HttpHandler):Observable>{
    const authReq = req.clone({
      url: (req.url + '&token=ujusaruu19')  //对任意请求的url添加token参数
    });

    return next.handle(authReq).pipe(mergeMap((event: any) => {
        if (event instanceof HttpResponse && event.status != 200) {
          return ErrorObservable.create(event);
        }
        return Observable.create(observer => observer.next(event)); //请求成功返回响应
      }),
      catchError((res: HttpResponse) => {   //请求失败处理
        switch (res.status) {
          case 401:
            break;
          case 200:
            console.log('业务错误');
            break;
          case 404:
            break;
          case 403:
            console.log('业务错误');
            break;
        }
        return ErrorObservable.create(event);
      }));
  }
}

  2.导入提供器中,app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import {InterceptorService} from "./interceptor.service";
import {HTTP_INTERCEPTORS, HttpClientModule} from "@angular/common/http";
import { TestComponent } from './test/test.component';


@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    {provide:HTTP_INTERCEPTORS,useClass:InterceptorService,multi:true}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

  3.结束,在组件中使用httpClient请求会自动拦截,拦截处理在InterceptorService.ts操作

转载于:https://www.cnblogs.com/changyaoself/p/8539048.html

你可能感兴趣的:(angular4 httpclient拦截器)