【发布时间】:2018-09-25 04:26:11
【问题描述】:
我正在使用 Angular HttpClient 将一些数据存储在服务器中,但我遇到了一条重复的指令。保存过程如下:
if(client is new){
//promise starts
store client and retrieve id
if(client has companion){
//promise starts
store companion and retrieve id
//promise starts
store product with previous retrieved id
}
//promise starts
store product with only client id
}else{
//promise starts
store product
}
正如您所见,“商店产品”指令重复了 3 次,因为我需要在继续之前从服务器返回信息。 以下是实际代码:
//Check if the client is new
if (this.rent.client.id === 0) {
this.clientServce.saveClientToDatabase(this.rent.client)
.subscribe((results) => {
//Store the new client Id
this.rent.client.id = results.clientID;
//Check if companion exists and save it to database
if (this.rent.companion.id !== -1) {
this.clientServce.saveCompanionToDatabase(this.rent.companion)
.subscribe((companionResults) => {
this.rent.companion.id = companionResults.clientID;
//Save te rent
this.rentServices.saveRentToDatabase(this.rent).subscribe()
})
} else {
//Save te rent
this.rentServices.saveRentToDatabase(this.rent).subscribe();
}
})
} else {
//Save te rent
this.rentServices.saveRentToDatabase(this.rent).subscribe();
}
它看起来确实可读。那么如何才能管理客户端和同伴存储并最终以可读的方式存储产品呢?
【问题讨论】:
-
可能会解构
this以便属性名称变短 -
1.那些不是承诺;您正在订阅,它们是可观察的。 2. 研究 observables 的操作符,你可以用一些地图把它弄平。
标签: javascript angular promise