如何确保Angular服务构造函数中的异步初始化完成? [英] How can I ensure that async initialization in the Angular service constructor is completed?

查看:265
本文介绍了如何确保Angular服务构造函数中的异步初始化完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

专家,请告诉我如何在类中调用其他函数时确保服务构造函数中的异步初始化完成?

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

正如您所看到的,与stomp服务器的连接是在构造函数。之后,邀请该服务的客户(组件)订阅感兴趣的主题。当然,在连接完全建立之前,对订阅功能的调用没有意义。

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.

更新:
它也是保持.connect方法只调用一次很重要。否则它会创建两个连接。

Update: It is also important to keep .connect method called only once. Otherwise it creates two connections.

推荐答案

通过承诺与stomp客户端进行每次交互,例如:

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

这篇关于如何确保Angular服务构造函数中的异步初始化完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆