如何返回功能级别?

时间:2016-06-26 05:34:07

标签: meteor typescript angular rxjs5 angular2-meteor

我有一个函数loadMessages,我希望它返回Observable

  loadMessages(chatId: string): Observable<Message[]> {
    console.log('1');

    this.autorun(() => {
      const handle = this.subscribe('messages', chatId);

      if (handle.ready()) {
        console.log('2');

        const messages = Messages.find().fetch();
        return Observable.of(messages);  // here return is not for this function, which is useless
      }
    });

    console.log('3');  // I don't want this line run immediately

    // I wish I can return here, but I cannot
  }

如何返回功能级别?

此外,现在订单是1 - &gt; 3 - &gt; 2.有没有办法运行1 - &gt; 2,等到那里我得到数据?

1 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情:

loadMessages(chatId: string): Observable<Message[]> {
  console.log('1');

  return Observable.create(observer => {
    this.autorun(() => {
      const handle = this.subscribe('messages', chatId);

      if (handle.ready()) {
        console.log('2');

        const messages = Messages.find().fetch();
        observer.next(messages)
      }
    });
  });
}

非常简单的例子是http://plnkr.co/edit/GADtB8QCTnNubtRu9SFv?p=preview