在使用 Angular 的可观察量进行修补/放置之前,您如何检查数据库中的数据?



这是我遇到的一个非常简单的问题,我只是不知道如何用可观察性尽可能无缝地做到这一点。我想检查我的数据库中的属性值。如果它存在,我将用新数据对其进行修补。如果没有,我会将新数据放入(将属性值添加到数据库中(。我正在运行Angular 10.0.7,并使用httpClient。

下面是我想做的:

saveData(data: DataObject) {
this.httpClient.get<DataObject>(
this.DATA_BASE_URL + this.user.username + ".json"
).subscribe(response => {
response.propertyName = data;
if (response.hasOwnProperty("propertyName")) {
this.httpClient.patch(
this.TEST_DB_URL + this.user.username + ".json",
response
).subscribe(r => {
console.log(r);
})
} else {
this.httpClient.put(
this.TEST_DB_URL + this.user.username + ".json",
response
).subscribe(r => {
console.log(r);
})
}
})
}

我不确定在subscribe((回调中添加http调用是否正确。有没有更传统或更有效的方法来实现这种模式?感谢阅读!

您可以使用switchMap,switchMap将一个调用的一个响应更改为内部调用的另一个响应

this.httpClient.get<DataObject>(
this.DATA_BASE_URL + this.user.username + ".json"
).pipe(switchMap(response => {
//with the response
response.propertyName = data;
if (response.hasOwnProperty("propertyName")) {
return this.httpClient.patch(
this.TEST_DB_URL + this.user.username + ".json",response
))
} else {
return this.httpClient.put(
this.TEST_DB_URL + this.user.username + ".json",response
)
}
})).subscribe(r => {
console.log(r);
})

最新更新