【发布时间】:2018-01-06 04:05:07
【问题描述】:
我有一个 Angular 应用程序,它向 Http 服务发出请求并在另一个 Http 服务上调用 switchMap。由于某种原因,switchMap 中的请求仅在第一次调用父调用时运行。否则父请求会触发而 switchMap 不会触发,代码如下:
this._receivableService.newTenantDebitCredit(tenantCredit)
.take(1)
.switchMap(result =>
// Refresh the lease receivables before giving result
this._receivableService.getAll({
refresh: true,
where: { leaseId: this.leaseId }
}).take(1).map(() => result)
)
.subscribe(
...
)
如何在每次调用上面的 newTenantDebitCredit 方法时运行 switch 映射中的 getAll 请求?
编辑:这是在click 上调用的函数的全部内容。当我第一次单击给定单元的按钮时,两种方法都会执行。如果我尝试一个已经调用了该方法的单元(没有刷新),则只执行第一个方法。我意识到很多事情可能还不清楚,目前这是一个相当大的项目。
public submitTenantCredit() {
this.isLoading = true;
let tenantCredit: NewTenantDebitCreditData;
let receivableDefinitions: ReceivableDefinition[] = [];
// construct receivable defintions for NewTenantDebitData model
receivableDefinitions = this._constructReceivableDefinitions();
// construct data we will be POSTing to server.
tenantCredit = new NewTenantDebitCreditData({
siteId: this._apiConfig.siteId,
leaseId: this.leaseId,
isCredit: true,
receivables: receivableDefinitions,
reason: this.actionReason
});
// make service call and handle response
this._receivableService.newTenantDebitCredit(tenantCredit)
.take(1)
.switchMap(result =>
// Refresh the lease receivables before giving result
this._receivableService.getAll({
refresh: true,
where: { leaseId: this.leaseId }
}).take(1).map(() => result)
)
.take(1)
.subscribe(
(receivables) => {
this.closeReasonModal();
let refreshLeaseId = this.leaseId;
this.leaseId = refreshLeaseId;
this.isLoading = false;
this.refreshBool = !this.refreshBool;
this._debitCreditService.refreshUnitInfo();
this._notifications.success(`The tenant credit for ${this.customerName} - Unit ${this.unitNumber} was submitted successfully`);
},
(error) => {
console.error(error);
this.isLoading = false;
}
)
}
如果有帮助,newTenantDebitCredit() 是 HTTP POST 请求,getAll() 是 GET 请求。
【问题讨论】:
-
可以尝试将
getAll包裹在Observable.defer中吗?文档reactivex.io/documentation/operators/defer.html -
defer 只是冻结了请求。
-
你能提供这个的代码吗?_receivableService.newTenantDebitCredit
-
@Zachscs 正如@FanCheung 指出的,还请提供
ReceivableService的样子;至少这里使用的两种方法。 -
应收款服务扩展了有自己定义的基础 API 服务。这对 SO 来说可能不是一个好问题。
标签: javascript angular rxjs