Angular 2将服务注入扩展类(BaseRequestOptions)

时间:2016-07-18 12:24:23

标签: typescript dependency-injection angular

我有以下代码扩展BaseRequestOptions类:

import { Injectable } from '@angular/core';

@Injectable()
export class AppRequestOptions extends BaseRequestOptions {
    constructor(private serviceA:ServiceA) {       
        super();        
    }   
    merge(options?: RequestOptionsArgs): RequestOptions {        
        console.log(this.serviceA);
        //this.serviceA.myCustomMethod();
        return super.merge(options);
    }
}

当我引用this.serviceA时,该值为undefined。当我将相同的服务注入其他服务/组件时,它按预期工作。

以下是完整的引导代码:

import { Injectable } from '@angular/core';
import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
import { APP_ROUTER_PROVIDERS  } from './routes';
import { HTTP_PROVIDERS, BaseRequestOptions, RequestOptions, RequestOptionsArgs, Headers } from '@angular/http';
import { ServiceA } from './ServiceA';

@Injectable()
export class AppRequestOptions extends BaseRequestOptions {
    constructor(private serviceA:ServiceA) {       
        super();        
    }   
    merge(options?: RequestOptionsArgs): RequestOptions {        
        console.log(this.serviceA);
        //this.serviceA.myCustomMethod();
        return super.merge(options);
    }
}

bootstrap(AppComponent, [
    APP_ROUTER_PROVIDERS,
    HTTP_PROVIDERS,  
    ServiceA,
    { provide: RequestOptions, useClass: AppRequestOptions }
]).catch(err => console.error(err));

ServiceA声明:

import { Injectable } from '@angular/core';

@Injectable()
export class ServiceA {
    myCustomMethod() {

    }
}

我使用的是Angular版本 2.0.0-rc.4

我不确定是不是因为我正在扩展一个类并将其标记为@Injectable()

我已经检查过,我能找到的唯一相关问题是:

  

Inject service inside a service inside a service in my Angular 2 application

     

Angular 2: Inject Service to another service. (No provider error)

更新

似乎它与一个开放的bug有关:https://github.com/angular/angular/issues/8925

2 个答案:

答案 0 :(得分:3)

有一个开放的错误:https://github.com/angular/angular/issues/9758

尽管正确设置了依赖项注入的元数据,但元素不会在构造函数级别提供给类实例。

@Injectable()
export class AppRequestOptions extends BaseRequestOptions {
  constructor(private serviceA:ServiceA) {       
    super();        
    console.log(Reflect.getMetadata('design:paramtypes', AppRequestOptions));
    console.log(Reflect.getMetadata('parameters', AppRequestOptions));
  }

  (...)
}

有关详细信息,请参阅此plunkr:https://plnkr.co/edit/hcqAfsI7u88jbjScq6m3?p=preview

修改

如果您使用RequestOptions课程而非BaseRequestOptions课程,则会有效:

@Injectable()
export class AppRequestOptions extends RequestOptions {
  constructor(private serviceA:ServiceA) {       
    super();        
  }   

  (...)
}

请参阅此plunkr:https://plnkr.co/edit/laP04kqUCOR5qbFgo0iM?p=preview

答案 1 :(得分:1)

这与我在这里回答的问题非常相似:Injected dependency is undefined when extending BaseRequestOptions

定义提供者时还要定义所需的依赖关系,因此提供者定义中的对象如下所示:

{
 provide: RequestOptions,
 useClass: AppRequestOptions,
 deps: [ServiceA]
}