[英]Angular 2 - Observable to Promise fails
I'm struggling with converting an observable into a promise. 我正在努力将一个可观察者转变成一个承诺。 I know that there's the toPromise()
function on any observable
but when I use this function it returns me ZonedAwarePromise
with the properties: 我知道在任何observable
上都有toPromise()
函数,但是当我使用这个函数时,它返回ZonedAwarePromise
的属性:
__zone_symbol_state: null
and __zone_symbol_value: Array[0]
__zone_symbol_state: null
和__zone_symbol_value: Array[0]
Also, the then
part of the promise never gets fired. 此外, then
承诺的一部分,永远不会被解雇。
Concrete Situation 具体情况
I want to send an http-api-request that reads a file and returns its content inside the Promise: 我想发送一个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);
});
}
}
Calling this promise like so: 像这样称呼这个承诺:
const fileName = '...';
this.fileService.getData(fileName).then( content => {
console.log(content); // never gets fired!
});
I already tried different variations like replacing return
with resolve(...)
or Promise.resolve(...)
and now I have no idea left how to fulfill this promise correctly in order to get the then
part working. 我已经尝试了不同的变体,比如用resolve(...)
或Promise.resolve(...)
替换return
,现在我不知道如何正确地履行这个承诺,以便让then
部分工作。
Thank you in advance for any help and ideas! 提前感谢您的任何帮助和想法!
in the new Promise
callback you have to resolve : 在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 )
});
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.