我想编写某种广播机制来在我的用户上下文中动态创建和使用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' –