我试图从一个数组上的另一个observable返回一个Observable。我使用数组来查找两个值并进行计算。目前我正在使用一个很好的Promise但是为了我自己的理解,我想知道它是如何完成的。
如何转换以下返回Promise的代码
convertToCurrency(fromCurrency: string, toCurrency: string) {
return new Promise((resolve, reject) => {
this.getQuotes()
.subscribe(quotes => {
let usdFrom = quotes.filter(val => {
return val.code.substring(3, 6) == fromCurrency;
})[0].quote;
let usdTo = quotes.filter(val => {
return val.code.substring(3, 6) == toCurrency;
})[0].quote;
let converted = usdTo / usdFrom;
resolve(converted);
}, error => reject());
});
}
进入这个:
convertToCurrency(fromCurrency: string, toCurrency: string): Observable<number> {
...
}
答案 0 :(得分:1)
它与您已经做过的承诺几乎相同。
convertToCurrency(fromCurrency: string, toCurrency: string): Observable<number> {
return new Observable<number>(observer => {
this.getQuotes()
.subscribe(quotes => {
let usdFrom = quotes.filter(val => {
return val.code.substring(3, 6) == fromCurrency;
})[0].quote;
let usdTo = quotes.filter(val => {
return val.code.substring(3, 6) == toCurrency;
})[0].quote;
let converted = usdTo / usdFrom;
observer.next(converted);
}, error => observer.error(error));
});
}