【问题标题】:Angular2: Return Observable in PromiseAngular2:在 Promise 中返回 Observable
【发布时间】:2016-07-13 15:00:46
【问题描述】:

我有以下代码。

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<Observable< > >

我只想知道如何订阅这个 observable,目前我已经尝试过:

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

但当然它不起作用,因为结果不是可观察的,所以有人知道如何管理这个问题吗?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    一个可观察的承诺......这很好:)试试这个:

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

    【讨论】:

    • 谢谢你,非常合乎逻辑,当你给我答案时啊啊。有没有更好的方法来做到这一点,而无需承诺观察到? :p
    猜你喜欢
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多