angular2+项目实用操作笔记(四) http拦截器的使用

在services文件夹下新建一个文件夹http-interceptors,在其中创建一个通常状态下的拦截器文件,下图代码拦截器对请求信息不做任何处理

 // common.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class CommonInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {
    return next.handle(req);
  }
}

需要处理请求信息需要使用do someing替换req,例如给所有请求添加withCredentials跨域可能

// common.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class CommonInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {
    return next.handle(req.clone({
      withCredentials: true
    }));
  }
}

如果设置的拦截器为一个或者多个,在文件夹下新建index文件,将拦截器的处理作为数组成员传入

 // index.ts
import { CommonInterceptor } from './common.interceptor';
import { HTTP_INTERCEPTORS } from '@angular/common/http';

export const httpInterceptorProvides = [
  { provide: HTTP_INTERCEPTORS, useClass: CommonInterceptor, multi: true}{ provide: HTTP_INTERCEPTORS, useClass: CommonInterceptor1, multi: true}{ provide: HTTP_INTERCEPTORS, useClass: CommonInterceptor2, multi: true}
];

之后将httpInterceptorProvides导入servicesModule的providers中就可以正常使用了

import { httpInterceptorProvides } from './http-interceptors/index';
import { NgModule, InjectionToken, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

export const API_CONFIG = new InjectionToken('ApiConfigToken');
export const WINDOW = new InjectionToken('WindowToken');

@NgModule({
  declarations: [],
  imports: [],
  providers: [
    {
      provide: API_CONFIG, useValue: 'http://localhost:3000/'
    },
    {
      provide: WINDOW,
      useFactory(platfromId: object): Window | object {
        return isPlatformBrowser(platfromId) ? window : {};
      },
      deps: [PLATFORM_ID]
    },
    httpInterceptorProvides
  ],
})
export class ServicesModule { }

仅作笔记,感谢指正

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值