在HttpInterceptor中使用Service - Angular2

时间:2017-08-15 15:42:13

标签: angular service angular-http-interceptors

我有一个像这样开始的Httpinterceptor:

@Injectable()
export class InterceptedHttp extends Http {

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

我想使用我在许多其他组件中创建和使用的服务。如果我将我的服务添加到构造函数中,就像我通常那样,我会得到一个异常。显然这是因为构造函数不能与扩展类不同:

  

错误:提供的参数与呼叫目标的任何签名都不匹配。

是否仍然可以在我的InterceptedHttp类中使用服务?

1 个答案:

答案 0 :(得分:0)

不再建议扩展Http。如果您使用的是角度4.3+,则应实现HttpInterceptor

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';

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

https://angular.io/guide/http#intercepting-all-requests-or-responses