[英]Injecting services into services in angular2
我想編寫某種廣播機制來動態創建和使用我的用戶上下文中的EventEmitter
。 為此,我注入了一個EmitterService
@Injectable()
export class BroadcastService implements OnInit {
private _emitters: { [channel: string]: EventEmitter<any> } = {};
constructor() {}
get(channel: string): EventEmitter<any> {
if (!this._emitters[channel]) {
this._emitters[channel] = new EventEmitter();
}
return this._emitters[channel];
}
ngOnInit() { }
}
我的組件結構如下所示:
[root]
| |
[comp-a][comp-b]
在我的root
組件中,我注入BroadcastService
以確保每個子組件使用相同的廣播信道。 此外還注入了其他服務,如AuthService
(在root
也是如此,這基本上是我的用戶上下文)
@Component({
provider: [BroadcastService, AuthService]
})
AuthService
(和其他人)正在使用BroadcastService
來發送事件:
@Injectable()
export class AuthService extends BaseService {
constructor(
http: Http,
@Inject(BroadcastService) private emitterService: BroadcastService)
{
super(http);
}
...
// Example usage of Broadcast
login(username: string, password: string) {
// do the login, when successfully:
this.emitterService.get("online").emit(true);
}
}
我得到的錯誤: EXCEPTION: Cannot resolve all parameters for 'AuthService'(Http, undefined @Inject(undefined)). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'AuthService' is decorated with Injectable.
EXCEPTION: Cannot resolve all parameters for 'AuthService'(Http, undefined @Inject(undefined)). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'AuthService' is decorated with Injectable.
我嘗試了什么:
BroadcastService
,結果相同 最奇怪的部分是,這適用於我的其他服務之一,而不是與其他服務一起工作(好吧,我沒有嘗試所有,但我試過的那些不起作用)。 你有什么線索可能是什么問題嗎? 或者這可能只是一個錯誤(我在2.0.0-beta.2中使用angular2)
好像需要forwardRef
@Injectable()
export class AuthService extends BaseService {
constructor(
http: Http,
@Inject(forwardRef(() => BroadcastService)) private emitterService: BroadcastService)
{
super(http);
}
...
// Example usage of Broadcast
login(username: string, password: string) {
// do the login, when successfully:
this.emitterService.get("online").emit(true);
}
}
也可能(或代替)有必要
@Component({
provider: [BroadcastService, AuthService]
})
取決於您的代碼組織方式。 當每個類在其自己的文件中定義時,這不是必需的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.