2016-07-13 113 views
3

我有以下代碼。Angular2:Return Promise中可觀察

getListCategoryOfQuestion() { 
    return this.authService.getToken() 
     .then(token => { 
      let headers = new Headers(); 
      headers.append('Authorization', `Bearer ${token}`); 
      return this.http.get('http://localhost:3333/question/getCategories', {headers:headers}) 
       .map(res => res.json()) 
       .catch(this.handleError); 
     }) 
     .catch(this.handleError); 
} 

我知道我無法從promise中返回同步值,但可觀察的是異步的。這個函數的返回類型爲Promise<Observable< > >

我只是想知道如何訂閱此觀察到,此刻我已經試過這樣:

loadCategory(){ 
    this.questionDBService.getListCategoryOfQuestion() 
     .subscribe(data => { 
      this.categories = data; 
      console.log(data); 
     }); 
} 

但是,當然,它不工作,因爲結果是不是可觀察的,所以任何人都知道如何解決這個問題?

回答

3

允諾可觀察......這很好:)試試這個:

loadCategory(){ 
    this.questionDBService.getListCategoryOfQuestion().then((observer) => { 

     observer.subscribe((data) => { 
      this.categories = data; 
      console.log(data); 
     }); 

    }); 

} 
+0

謝謝你,所以邏輯,當你給我的答案AHAH。有沒有更好的方法來做到這一點,而不是將可觀察的事物放在承諾中? :p –