Answer the question
In order to leave comments, you need to log in
How to make sure asynchronous initialization in Angular service constructor is completed?
Connoisseurs, please tell me how to make sure that asynchronous initialization in the service constructor is completed when other functions in the class are called?
Code example:
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));
}
Answer the question
In order to leave comments, you need to log in
The constructor must not be asynchronous. Carry out initialization by a separate method, to which we already give the opportunity to subscribe.
1. As correctly noted in the previous answer - the constructor should not be asynchronous. Move the initialization to a separate method.
2. Why can't you sign before a connection is established? Who said that? I don’t know about the client you are using, but you can declare your Subject (from RxJs), subscribe to it, and it will already send events from the socket when the connection is established. Those. only the service that created it subscribes to socket events after the connection is established. All others subscribe to the events of this service. The service forwards all events that come from the socket to its subscribers.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question