我有以下扩展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()
?
我已经检查过了,我能找到的唯一相关问题是:
在我的Angular 2应用程序中,在服务内部注入服务
Angular 2:将服务注入另一个服务。(无提供商错误)
更新
似乎与一个打开的bug有关:https://github.com/angular/angular/issues/8925
这方面有一个开放的bug: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.
这与我在这里回答的问题非常相似:在扩展BaseRequestOptions 时,注入的依赖项是未定义的
在定义提供者时,还定义了所需的依赖项,因此提供者定义中的对象看起来像:
{
provide: RequestOptions,
useClass: AppRequestOptions,
deps: [ServiceA]
}