Javascript 角度2:承诺中可观察到的回报
我有以下代码Javascript 角度2:承诺中可观察到的回报,javascript,angular,Javascript,Angular,我有以下代码 getListCategoryOfQuestion() { return this.authService.getToken() .then(token => { let headers = new Headers(); headers.append('Authorization', `Bearer ${token}`); return this.http.get('http://
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返回同步值,但observable是异步的。此函数的返回类型为Promise>
我只是想知道如何订阅这个可观察的,目前我已经尝试过了:
loadCategory(){
this.questionDBService.getListCategoryOfQuestion()
.subscribe(data => {
this.categories = data;
console.log(data);
});
}
但当然,它不起作用,因为结果是不可观察的,所以有人知道如何处理这个问题吗?一个可观察的承诺。。。很好:)试试这个:
loadCategory(){
this.questionDBService.getListCategoryOfQuestion().then((observer) => {
observer.subscribe((data) => {
this.categories = data;
console.log(data);
});
});
}
谢谢你,这么合乎逻辑,当你给我答案的时候啊哈。有一种更好的方法可以做到这一点,而无需在承诺中加入可观察的内容:P