1

我有一个函数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 -> 3 -> 2。有什么方法可以运行 1 -> 2,然后在那里等到我得到数据?

4

1 回答 1

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

于 2016-06-26T06:56:47.270 回答