请专家告诉我,在调用类中的其他函数时,如何确保服务构造函数中的异步初始化完成?
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 的连接是在构造函数中建立的。之后,该服务的客户(组件)被邀请订阅感兴趣的主题。当然,在连接完全建立之前,调用 subscribe 函数是没有意义的。
Update:保持 .connect 方法仅调用一次也很重要。否则它会创建两个连接。
通过承诺与 stomp 客户端进行每次交互,例如:
constructor() {
...
this.stomp = new Promise(resolve => {
stompClient.connect({}, () => resolve(stompClient));
});
}
subscribe(...) {
this.stomp.then(stompClient => stompClient.subscribe(...));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)