我想按字符串顺序使用此Angular代码并获取返回值:
transaction: ITransaction = new Transaction();
merchant: IMerchant;
const transactionid = this.route.snapshot.params['id'];
if (!transactionid) {
this.router.navigate(['panel', 'transactions']);
}
this.transactionService.get(transactionid)
.subscribe(value => {
if (value != null) {
this.transaction = value;
}
});
this.merchantService.get(this.transaction.merchant_id)
.subscribe(value => {
if (value != null) {
this.merchant = value;
}
});
console.log('value ' + this.merchant.name);
但是我的商人ID为空,第二个请求未正确执行。
首先,我想使用来自http链接的id加载transactionService.get(params ['id'])。第二,在加载对象事务时,我想使用从第一个请求加载的unique_id加载get(transaction.merchant_id)。我尝试过:
this.route.params.pipe(
tap( params => {
if (params['id']) {
return this.transactionService.get(params['id']);
} else {
return of(null);
}
}),
switchMap( value => this.merchantService.get(value.merchant_id) )
);
实施此操作的适当理由是什么?
答案 0 :(得分:1)
使用mergeMap
运算符来级联可观察对象。另外,使用tap
运算符将结果保存在类中。
this.transactionService.get(transactionid).pipe(
tap(transaction => {
this.transaction = transaction;
}),
mergeMap(transaction => {
if (transaction != null) {
return this.merchantService.get(transaction.merchant_id);
}
else {
return of(null);
}
})
).subscribe(merchant => {
if (merchant != null) {
this.merchant = merchant;
}
});