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.
Make every interaction with the stomp client through a promise, e.g.: