G
G
godyear2017-07-13 06:52:38
JavaScript
godyear, 2017-07-13 06:52:38

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));
  }

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

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Negwereth, 2017-07-13
@Negwereth

The constructor must not be asynchronous. Carry out initialization by a separate method, to which we already give the opportunity to subscribe.

A
Aleksei Podgaev, 2017-07-13
@alexiusp

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 question

Ask a Question

731 491 924 answers to any question