使用自定义提供程序在另一个中注入服务

时间:2017-08-04 19:01:48

标签: angular angular-http-interceptors

我正在尝试在我的项目中扩展一些http功能。服务看起来像

import { Injectable } from "@angular/core";
import { Http, Headers, Request, ... } from "@angular/http";
import { AuthService } from './auth.service';

@Injectable()
export class HttpInterceptor extends Http {
  constructor(
    backend: ConnectionBackend,
    defaultOptions: RequestOptions,
    authService: AuthService) {
    super(backend, defaultOptions);
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return super.get(url, this.getRequestOptionArgs(options));
  }

  getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs() {
    //some logic using the auth service
    console.log(this.authService); // print undefined 
  }

我的工厂代码

export function HttpFactory(
  xhrBackend: XHRBackend,
  requestOptions: RequestOptions,
  authService: AuthService): Http {
  return new HttpInterceptor(xhrBackend, requestOptions, authService);

}

我的app.module看起来像这样

@NgModule({
    imports: [....],
    declarations: [....],
    providers: [
         .
         .
     {
       provide: Http,
       useFactory: HttpFactory,
       deps: [XHRBackend, RequestOptions]
     }]

代码抛出错误“无法从undefined中读取属性getAccessToken”,然后我尝试记录服务本身,并且我在前面的代码中记录了undefined。

完全赞赏任何帮助。

0 个答案:

没有答案