gpt4 book ai didi

Angular2 - 当两种服务相互需要时

转载 作者:太空狗 更新时间:2023-10-29 18:26:57 24 4
gpt4 key购买 nike

这是我的主要组件(根组​​件)。在这里,我声明了一些应该可以通过整个应用程序访问的服务。

@Component({
...
providers: [
WebSocketService,
...
AuthenticationService,
]
})
export class MainComponent { ... }

而且 - 确保每个人都明白 - 我正在做:

bootstrap(MainComponent, [...]);

WebSocketService 和AuthenticationService 都使用@Injectable() 注解。一切正常,直到我发现这两种服务需要彼此。AuthenticationService 需要WebSocketService 与后端服务器通信,WebSocketService 需要AuthenticationService 检查用户是否登录等。

因此,我收到了该错误消息:

EXCEPTION: Cannot resolve all parameters for 'AuthenticationService'(undefined). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'AuthenticationService' is decorated with Injectable.

这是 AuthenticationService 的片段。 WebSocketService 看起来很相似。

@Injectable()
export class AuthenticationService implements OnInit {

constructor(private webSocketService:WebSocketService) {
}
...
}

我知道,对于这种情况(第三方服务等)有不同的,也许更好的解决方案,但这不是我的问题的重点。我想知道是否有一种方法可以像我介绍的那样使用 Angular2 将两个服务相互注入(inject)?

最佳答案

更新(未测试)

bootstrap(AppComponent, [
provide(WebSocketService, {useFactory: () => {
let as = new AuthenticationService();
let ws = new WebSocketService(as);
as.webSocketService = ws;
return ws;
}}),
provide(AuthenticationService, {useFactory: {(ws) => {
return ws.authenticationService;
}, deps: [WebSocketService]);
})
]);

原创(仅适用于类型依赖,不适用于实例依赖)

循环引用需要使用forwardRef解决(需要从angular2/core导入

constructor(@Inject(forwardRef(() => WebSocketService)) private webSocketService:WebSocketService) {

关于Angular2 - 当两种服务相互需要时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36238773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com