admin管理员组文章数量:1406308
Experts, please tell me how to make sure that asynchronous initialization in the service constructor is plete 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 (ponents) 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.
Experts, please tell me how to make sure that asynchronous initialization in the service constructor is plete 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 (ponents) 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.
Share Improve this question edited Jul 14, 2017 at 5:38 V. D. asked Jul 13, 2017 at 20:02 V. D.V. D. 731 silver badge9 bronze badges1 Answer
Reset to default 7Make 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(...));
}
本文标签:
版权声明:本文标题:javascript - How can I ensure that async initialization in the Angular service constructor is completed? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745003425a2637118.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论