【发布时间】:2017-01-11 06:17:54
【问题描述】:
我有以下代码扩展 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)
更新
似乎它与一个开放的错误有关:https://github.com/angular/angular/issues/8925
【问题讨论】:
-
你用的是哪个版本的Angular2?
-
@ThierryTemplier 我正在使用 2.0.0-rc.4
-
AppRequestOptions 不是@Injectable。
-
是的,很确定,因为 AppRequestOptions 未标记为可注入。 estus 请做出你的回答:)
-
@estus 我已更新我的代码以将其标记为可注入,但它仍然无法正常工作。
标签: typescript dependency-injection angular