Angular 角度7/Rxjs:链接和嵌套观测值
我有一个交易数据集,我想用其他数据(如给定日期的汇率)来丰富它,并将其直接发布到我的api中。 但我只得到我的原始事务,没有任何修改,而且我对Angular和Rxjs还是新手。所以我需要一些操作员的帮助 我有一个按钮,可以从一个函数调用多个API:Angular 角度7/Rxjs:链接和嵌套观测值,angular,rxjs6,chain,Angular,Rxjs6,Chain,我有一个交易数据集,我想用其他数据(如给定日期的汇率)来丰富它,并将其直接发布到我的api中。 但我只得到我的原始事务,没有任何修改,而且我对Angular和Rxjs还是新手。所以我需要一些操作员的帮助 我有一个按钮,可以从一个函数调用多个API: //component.ts 公共点击(){ this.deposits=this.depositApi.getAllDeposits() .订阅( 结果=>{ map(x=>this.depositApi.enrichandsaveposit(x)
//component.ts
公共点击(){
this.deposits=this.depositApi.getAllDeposits()
.订阅(
结果=>{
map(x=>this.depositApi.enrichandsaveposit(x));
}
);
}
从本地api获取所有具有日期的原始事务。(本工程)
//存款服务
public getAllDeposits():可观察{
返回此.http.get(AppConfig.localJsonServerUrl+AppConfig.api.depositions)
.烟斗(
catchError(this.handleError('getAllDeposits',null))
);
}
在这里,我调用一个外部api来获取给定日期的汇率,然后进行一些计算并将其发布回本地api
但它从未进入合并地图部分
//存款服务
公共存款(存款:存款模型):可观察{
返回此.apiService.getHistoricEurRate(存款日期)
.烟斗(
合并映射(数据=>{
deposit.historicExchangeRate=data.rates.USD;
存款.exchangeRate=存款.sellAmount/存款.buyAmount;
deposit.sellAmountInUsd=deposit.sellAmountInUsd*data.rates.USD;
deposit.exchangeRateInUsd=deposit.exchangeRate*data.rates.USD;
返回此.saveLocalDeposit(存款);
}),catchError(this.handleError('enrichAndSaveLocalDeposit',deposit))
);
}
这里调用了外部api(这是可行的)
//apiService
public getRemoteExchangeRates():可观察{
返回此.http.get(AppConfig.exchangeRateApi+'/latest')
.烟斗(
catchError(this.handleError('getRemoteExchangeRates',null))
);
}
这是本地api的post。(从来没有达到这一点)
//存款服务
private saveLocalDeposit(存款:存款模型):可观察{
返回this.http.post
(
AppConfig.localJsonServerUrl+AppConfig.api.deposits,
押金
{headers:new-HttpHeaders().set('Accept','application/json')}
)
.烟斗(
catchError(this.handleError('saveLocalDeposit',存款))
);
}
问题在于,您从未订阅从enrichAndSaveDeposit
返回的可观察内容,因此从未进行http POST
分配并提供观察者函数(即使是空函数)就足够了
public click() {
this.deposits = this.depositApi.getAllDeposits()
.subscribe(
result => {
result.map(x => this.depositApi.enrichAndSaveDeposit(x).subscribe(() => {}));
}
);
}
Angular的HttpClient方法(get、post等)返回冷观测值,这意味着它们只在订阅时开始运行。这有两个重要原因:
- 除非您订阅从该HttpClient方法返回的可观察对象,否则不会发出HTTP请求
- 对HttpClient方法的每个订阅都将发出一个请求
下面是我对一个类似问题的回答,该问题概述了如何解决这个问题 此外,我想向您提供一个关于RXJ的提示,我认为这是当前问题的一部分。让我们看看您的代码,如下所示
public click() {
this.deposits = this.depositApi.getAllDeposits()
.subscribe(
result => {
result.map(x => this.depositApi.enrichAndSaveDeposit(x));
}
);
}
这段代码订阅可观察的GetAllDeposit,然后说当它返回一个值时,使用enrichAndSaveDeposit映射该值。然而,您的enrichAndSaveDeposit代码也是一个可观察的代码,因此正如上面所写的,它永远不会被调用,因为它从未被订阅过。下面我写了一些东西来解决这个具体的问题
public click() {
this.deposits = this.depositApi.getAllDeposits()
.subscribe(
result => {
result.map(x => {
this.depositApi.enrichAndSaveDeposit(x)
.subscribe( // this is the subscribe that is needed to make the second part of the chain work
enrichedResult => {
// do something with the enrichedResult here
}
);
};
}
);
}
希望这有帮助。谢谢。这有帮助!