Angular 2 - Observable to Promise失败

时间:2017-03-13 09:46:43

标签: angular promise rxjs observable angular2-http

我正在努力将观察力转化为承诺。我知道任何toPromise()都有observable函数,但是当我使用此函数时,它会返回ZonedAwarePromise个属性:

__zone_symbol_state: null__zone_symbol_value: Array[0]

此外,承诺的then部分永远不会被解雇。

具体情况

我想发送一个http-api-request,它读取一个文件并在Promise中返回它的内容:

public getData(fileName: string): Promise<any> {
    return new Promise( (resolve, reject) => {
        this.getHomeDirectory().then(homedir => {
            const fullFileName = homedir + fileName;
            const myApiRequest = "..." + fullFileName;
            return this.http.get(myApiRequest)
                        .map(this.extractData)
                        .toPromise()
                        .catch(this.handleError);
        });
    }
}

像这样召唤这个承诺:

const fileName = '...';
this.fileService.getData(fileName).then( content => {
    console.log(content); // never gets fired!
});

我已经尝试了不同的变体,例如将return替换为resolve(...)Promise.resolve(...),现在我不知道如何正确履行此承诺才能获得then部分工作。

提前感谢您的任何帮助和想法!

1 个答案:

答案 0 :(得分:0)

您需要解决的new Promise回调中的

 public getData(fileName: string): Promise<any> {
    return new Promise( (resolve, reject) => {
        this.getHomeDirectory().then(homedir => {
            const fullFileName = homedir + fileName;
            const myApiRequest = "..." + fullFileName;
            this.http.get(myApiRequest)
                        .map(this.extractData)
                        .catch(this.handleError)
                        .subsucribe(data =>  {
                            resolve(data )
                        });
        });
    }
}