我想編寫某種廣播機制來在我的用戶上下文中動態創建和使用EventEmitter
。要做到這一點我注入了EmitterService
在angular2中向服務注入服務
@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
分量I注入BroadcastService
以確保每個子組件使用相同的廣播信道。另外像AuthService
等業務都注入(在root
過,這基本上我的用戶上下文)使用的是BroadcastService
對發出事件
@Component({
provider: [BroadcastService, AuthService]
})
的AuthService
(及其他):
@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.
我試了一下:
- 把另一根組件在頂部的當前根組件注入
BroadcastService
那裏,同樣的結果 - 添加/刪除的@Inject的構造函數的參數,不改變
- 乞討和哭泣,並沒有幫助
最奇怪的部分是,這部作品與我的其他服務之一,不與他們的休息(當然,我沒有嘗試所有,但那些我試過沒有工作)。你有什麼線索可能是什麼問題?或者這也許只是一個錯誤(我使用angular2在2.0.0-beta.2)
你加'HTTP_PROVIDERS'到'引導(AppComponent,[...])'? '@Inject(BroadcastService)'是冗餘的AFAIK。 –
是的。我真的不知道,問題可能是什麼 – letmejustfixthat
我想這是源文件中的類的順序。 'AuthService'和'BroadcastService'是否在同一個文件中?改變這兩個類的順序或使用'forwardRef' –