3

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

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

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

bootstrap(MainComponent, [...]);

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

结果,我收到了该错误消息:

例外:无法解析“AuthenticationService”的所有参数(未定义)。确保所有参数都用 Inject 修饰或具有有效的类型注释,并且 'AuthenticationService' 用 Injectable 修饰。

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

@Injectable()
export class AuthenticationService implements OnInit {

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

我知道,对于这种情况(第三次服务等)有不同的甚至更好的解决方案,但这不是我的问题的重点。我想知道是否有一种方法可以使用 Angular2 以我提出的类似方式将两个服务相互注入?

4

1 回答 1

3

更新 (未测试)

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) {
于 2016-03-26T17:58:09.837 回答