首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用HttpModule的HttpInterceptor

使用HttpModule的HttpInterceptor
EN

Stack Overflow用户
提问于 2019-01-10 17:15:54
回答 1查看 428关注 0票数 0

在我的angular应用程序(angular版本5)中,我使用的是来自@angular/httpHttp。另外,我还以一种正常的方式添加了报头,比如

代码语言:javascript
复制
getHeaders(){
  let headers = new Headers();
  headers.append('authorization', 'Bearer '+this.authToken);
  headers.append('Content-Type', 'application/json');
  return headers;
}

现在我想改变这种方式,并考虑使用HttpInterceptor。据我所知,我们必须在HttpClient中使用它,但在我的angular应用程序中。到目前为止,我已经使用了Http。我们有没有办法用Http来实现HttpInterceptor

EN

回答 1

Stack Overflow用户

发布于 2019-01-10 17:45:57

以下是如何使用Http模块模拟Http拦截器。

代码语言:javascript
复制
// 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是从您创建的文件导入的)

代码语言:javascript
复制
 providers: [
    NotifyService,
    {
      provide: HttpInterceptor,
      useFactory:
        (backend: XHRBackend, defaultOptions: RequestOptions, notifyService: NotifyService) => {
        return new HttpInterceptor(backend, defaultOptions, notifyService);
      },
      deps: [ XHRBackend, RequestOptions, LoaderService, Store]
    }

并修改您的服务文件:

代码语言:javascript
复制
/ 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)
  }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54125311

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档