首页 > 解决方案 > 在使用 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 调用是否正确。有没有更传统或更有效的方法来实现这种模式?谢谢阅读!

标签: angulartypescripthttp

解决方案


您可以使用 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);
    })

推荐阅读