Typescript Angular2中的两个(或更多)异步调用
我在一个组件中有一个函数,它应该返回一个值(Promise)。 要获得该值,我需要来自两个不同来源的信息。 让源是一个API调用和一个数据库数据 方法如下:Typescript Angular2中的两个(或更多)异步调用,typescript,promise,angular2-services,Typescript,Promise,Angular2 Services,我在一个组件中有一个函数,它应该返回一个值(Promise)。 要获得该值,我需要来自两个不同来源的信息。 让源是一个API调用和一个数据库数据 方法如下: public getValue(): Promise<number> { return this.dataProvider.loadData().toPromise().then(data => { return data.feePerc }).then(feePerc => {
public getValue(): Promise<number> {
return this.dataProvider.loadData().toPromise().then(data => {
return data.feePerc
}).then(feePerc => {
let url = `${apiUrl}/mycontroller/value`
return new Promise<number>(resolve => {
return this.http.get(url)
.map(response => {
let value = response.json()
return resolve(value * (1 + (feePerc / 100)))
})
})
})
}
public getValue():承诺{
返回此.dataProvider.loadData().toPromise()。然后(数据=>{
返回数据.feePerc
}).然后(feePerc=>{
让url=`${APIRL}/mycontroller/value`
返回新承诺(解析=>{
返回此.http.get(url)
.map(响应=>{
让value=response.json()
返回解析(值*(1+(feePerc/100)))
})
})
})
}
它不起作用。
返回了feePerc值,但返回http.get可能是错误的,因为它是可观察的,而且如果我将其包装在一个承诺中,它也不起作用
实际上,map()函数从未出现过
我最初的想法是调用这两个异步函数,并使用一种信号量来返回最终结果,当我拥有这两个源时,但我仍在努力使用简单的链式解决方案
package.json:
- “@angular/core”:“4.2.5”
- “rxjs”:“5.4.2”
map()
从未被调用,因为您从未订阅可观察对象
这里使用的是Promissions反模式,而且无论如何都不需要Promissions,因为Observable本身就有链接Observable的方法
(顺便说一句,在第一次调用中使用toPromise()
是非常奇怪的,这是将可观测值转换为承诺的正确方法,但在第二次调用中不使用它)
你所需要的只是
public getValue(): Observable<number> {
const url = `${apiUrl}/mycontroller/value`;
return this.dataProvider.loadData()
.map(data => data.feePerc)
.switchMap(feePerc =>
this.http.get(url).map(response => response.json() * (1 + (feePerc / 100))));
}
public getValue():可观察{
constURL=`${apirl}/mycontroller/value`;
返回此.dataProvider.loadData()
.map(data=>data.feePerc)
.switchMap(feePerc=>
this.http.get(url.map)(response=>response.json()*(1+(feePerc/100));
}
请注意,Angular 2现在已经快2岁了。目前的版本是6.x。现在是升级的时候了,除其他外,切换到RxJS 6和HttpClient。map()
永远不会被调用,因为您永远不会订阅observable
这里使用的是Promissions反模式,而且无论如何都不需要Promissions,因为Observable本身就有链接Observable的方法
(顺便说一句,在第一次调用中使用toPromise()
是非常奇怪的,这是将可观测值转换为承诺的正确方法,但在第二次调用中不使用它)
你所需要的只是
public getValue(): Observable<number> {
const url = `${apiUrl}/mycontroller/value`;
return this.dataProvider.loadData()
.map(data => data.feePerc)
.switchMap(feePerc =>
this.http.get(url).map(response => response.json() * (1 + (feePerc / 100))));
}
public getValue():可观察{
constURL=`${apirl}/mycontroller/value`;
返回此.dataProvider.loadData()
.map(data=>data.feePerc)
.switchMap(feePerc=>
this.http.get(url.map)(response=>response.json()*(1+(feePerc/100));
}
请注意,Angular 2现在已经快2岁了。目前的版本是6.x。现在是升级的时候了,除其他外,切换到RxJS 6和HttpClient。正如建议的那样,在map()中添加.subscribe()。。。解决了这个问题。不管怎样,我还是切换到了可观察的解决方案(也是建议的)。。。解决了这个问题。无论如何,我还是切换到了可观察的解决方案(也建议)。