2016-06-26 3 views
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를 실행할 수있는 방법이 있습니까? 데이터를 가져올 때까지 기다려주십시오.

답변

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

+0

너무 감사합니다 여기! 완벽하게 작동합니다! –

관련 문제