具有HttpModule的HttpInterceptor

时间:2019-01-10 09:15:54

标签: angular http

在我的角度应用程序(角度版本5)中,我正在使用Http中的@angular/http。而且我也以正常方式附加标头

getHeaders(){
  let headers = new Headers();
  headers.append('authorization', 'Bearer '+this.authToken);
  headers.append('Content-Type', 'application/json');
  return headers;
}

现在,我想更改这种方式,并考虑使用HttpInterceptor。如我所知,我们必须将其与HttpClient一起使用,但要在我的角度应用程序中使用。到目前为止,我已经使用过Http。有什么方法可以用HttpInterceptor来实现Http

1 个答案:

答案 0 :(得分:0)

这是使用Http模块模拟Http拦截器的方法。

// create interceptor service

import { Injectable } from '@angular/core';
import {
  Http,
  ConnectionBackend,
  RequestOptions,
  RequestOptionsArgs,
  Response,
  Headers,
  Request
} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { environment } from '../../environments/environment';

// Shows Progress bar and notifications
import { NotifyService } from "./loader";

@Injectable()
export class HttpInterceptor extends Http {

  constructor(
    backend: ConnectionBackend,
    defaultOptions: RequestOptions,
    private notifyService: NotifyService
  ) {
    super(backend, defaultOptions);
  }

  // for get method
  
   get(url: string, options?: RequestOptionsArgs): Observable<any> {
    this.beforeRequest();
    return super.get(this.getFullUrl(url), this.customizeOptions(options))
      .catch(console.log('Ouch!!!'))
      .do((res: Response) => {
        console.log('Nothing can stop me');
      }, (error: any) => {
        console.log("I'm hit. where's my medicccc : - X");
      })
      .finally(() => {
        console.log('Finally we Won the war :-)')
      });
  }
  // write for post method here 
  
  // some other methods you can write here 
  
  // to handle error
  private onError(error: any): void {
    this.notifyService.popError();
  }

  private onFinally(): void {
    this.responseInterceptor();
  }
}

现在app.module中执行以下操作:(请注意:HttpInterceptor是从您创建的文件中导入的)

 providers: [
    NotifyService,
    {
      provide: HttpInterceptor,
      useFactory:
        (backend: XHRBackend, defaultOptions: RequestOptions, notifyService: NotifyService) => {
        return new HttpInterceptor(backend, defaultOptions, notifyService);
      },
      deps: [ XHRBackend, RequestOptions, LoaderService, Store]
    }

并修改您的服务文件:

/ imports here 
// .......

@Injectable()
export class DataService {

  constructor(public http: HttpInterceptor) {};
getData() {
    return this
      .http.get(`data?limit=20&offset=40`)
      // will hit the api on http://api.localhost.com:4000/data?limit=20&offset=40
      .map(res => res.json().data)
  }

}