简体   繁体   English

Angular2:承诺中的回归观察

[英]Angular2: Return Observable in Promise

i have the following code. 我有以下代码。

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);
}

I know that I can't return sync value from promise, but observable are async. 我知道我不能从promise返回同步值,但是observable是异步的。 The return of this function is of type Promise<Observable< > > 此函数的返回类型为Promise<Observable< > >

I just want to know how to subscribe to this observable, at the moment i have tried this: 我只是想知道如何订阅这个observable,目前我已经尝试过这个:

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

But of course it's not working because the result is not an observable, so anyone know how manage this problem ? 但当然它不起作用,因为结果不是可观察的,所以任何人都知道如何管理这个问题?

A promise with observable... that's nice :) try this: 一个可观察的承诺......这很好:)尝试这个:

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

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

    });

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM