2016-07-13 117 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 –