【发布时间】:2016-05-09 02:34:16
【问题描述】:
我想编写某种广播机制来在我的用户上下文中动态创建和使用EventEmitters。为此,我注入了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.
我尝试了什么:
- 将另一个根组件放在当前根组件的顶部以将
BroadcastService注入那里,结果相同 - 在构造函数参数中添加/删除@Inject,无更改
- 乞求哭泣,无济于事
最奇怪的是,这适用于我的其他服务之一,但不适用于其他服务(好吧,我没有尝试所有,但我尝试过的那些都不起作用)。你有什么线索可能是什么问题吗?或者这可能只是一个错误(我在 2.0.0-beta.2 中使用 angular2)
【问题讨论】:
-
您是否将
HTTP_PROVIDERS添加到bootstrap(AppComponent, [...])?@Inject(BroadcastService)是多余的 AFAIK。 -
是的。我真的不知道,问题可能是什么
-
我猜这是源文件中类的顺序。
AuthService和BroadcastService在同一个文件中吗?改变这两个类的顺序或者使用forwardRef
标签: angular