• 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<any>,next:HttpHandler):Observable<HttpEvent<any>>{
        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<any>) => {   //请求失败处理
            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操作

  • 相关阅读:
    数据降维和可视化
    聚类
    支持向量机的实现
    支持向量机核函数
    支持向量基
    倾斜类误差度量
    构建垃圾邮件分类器
    POJ 2955 Brackets (区间dp入门)
    POJ 3126 Prime Path (bfs+欧拉线性素数筛)
    POJ 1426 Find The Multiple (dfs??!!)
  • 原文地址:https://www.cnblogs.com/changyaoself/p/8539048.html
Copyright © 2020-2023  润新知