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

你离开我真会死。 提交于 2019-12-08 14:14:41

问题


Experts, please tell me how to make sure that asynchronous initialization in the service constructor is complete when calling other functions in the 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));
  }

As you can see, the connection to the stomp-server is established in the constructor. After that, customers (components) of this service are invited to subscribe to topics of interest. Naturally, the call to the subscribe function does not make sense until the connection is fully established.

Update: It is also important to keep .connect method called only once. Otherwise it creates two connections.


回答1:


Make every interaction with the stomp client through a promise, e.g.:

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

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


来源:https://stackoverflow.com/questions/45089976/how-can-i-ensure-that-async-initialization-in-the-angular-service-constructor-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!