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

Angular2 - when both services requires each other

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

@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 以我介绍的类似方式将两个服务相互注入?

更新 (未测试)

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) {