angular - 在使用 angular 的 observables 修补/放置之前,如何检查数据库中的数据?
问题描述
这是我遇到的一个非常简单的问题,我只是不知道如何使用 observables 尽可能无缝地做到这一点。我想检查我的数据库中的属性值。如果存在,我将用新数据对其进行修补。如果不是,我会将新数据放入(将属性值添加到数据库中)。我正在运行 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);
})
推荐阅读
- javascript - setTimeout 中的 setState 返回令人困惑的结果
- python - 如何将每个圆圈连接到pygame的左上角?
- c++ - 用 std::move 分配一个 unique_ptr 不起作用
- sql - 如何使用具有整数列名的表?
- android - 第一个代码和第二个代码有什么区别,为什么要添加getString?
- android - EditText 中的 getText 返回空值
- django - 在 Django 模板中将 Markdown 渲染为 HTML
- python - 查找 3D numpy 数组的 y 坐标的最大值和最小值
- angular - NgRx 测试 - 订阅回调在测试期间未更新
- c# - 如何通过 UWP 中的页面传递列表