【问题标题】:How to return to the function level?如何回到功能层面?
【发布时间】:2016-10-28 09:07:42
【问题描述】:

我有一个函数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,然后等到我得到数据?

【问题讨论】:

    标签: meteor typescript angular rxjs5 angular2-meteor


    【解决方案1】:

    你可以试试这样的:

    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

    【讨论】:

      猜你喜欢
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 2019-10-16
      • 2020-11-14
      • 2011-12-14
      相关资源
      最近更新 更多