如何确保 Angular 服务构造函数中的异步初始化完成?

How can I ensure that async initialization in the Angular service constructor is completed?

请高手告诉我,在class中调用其他函数时,如何确保服务构造函数中的异步初始化完成?

  constructor() {
    var sock = new SockJS(this._chatUrl);
    this.stompClient = Stomp.over(sock);
    this.stompClient.connect({}, function () {
    });
  }

  public subscribe(topicName: string, messageReceived) {
    this.stompClient.subscribe('/topic/' + topicName, function (message) {
      messageReceived(message);
    })
  }

  public sendMessage(msgDestId: string, message) {
    this.stompClient.send("/app/" + msgDestId, {}, JSON.stringify(message));
  }

如您所见,在构造函数中建立了到 stomp-server 的连接。之后,邀请该服务的客户(组件)订阅感兴趣的主题。自然地,在连接完全建立之前,对订阅函数的调用是没有意义的。

更新: 保持 .connect 方法只被调用一次也很重要。否则它会创建两个连接。

通过承诺与 stomp 客户端进行每次交互,例如:

constructor() {
    ...
    this.stomp = new Promise(resolve => {
        stompClient.connect({}, () => resolve(stompClient));
    });
}

subscribe(...) {
    this.stomp.then(stompClient => stompClient.subscribe(...));
}