javascript - How can I ensure that async initialization in the Angular service constructor is completed? - Stack Overflow

admin2025-04-19  0

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 badges
Add a ment  | 

1 Answer 1

Reset to default 7

Make 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(...));
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745003447a279370.html

最新回复(0)