将异步POST放入数据库时​​出现问题

时间:2019-05-08 08:17:18

标签: javascript angular asynchronous post

当前,我有以下代码,该代码基本上将表单的结果发布到数据库中,但是有时表单中的某些字段可以为null,因此Im不得不在更新之前检查对象并按顺序保存变量让他们不为空。

onUpdateClick(updateHash, updateHeight, updateSize, updateTime) {
    //this is the url where the post will be made
    this.url = "http://localhost:3000/api/blockinfo/" + updateHash.toString();

    //those are the variables in the object stored in the database (url)
    var height;
    var size;
    var time;

    //this is the original object before any modification
    var nullCase;

    nullCase = this.http.get(this.url)

    //those if's mean that if one of the fields in the form is null (non filled) , I will check for the object before the modification (nullCase),and use its previous values in the update
    if (updateHeight == null) {
      height = Number(nullCase.height)
    } else {
      height = Number(updateHeight)
    }

    if (updateSize == null) {
      size = Number(nullCase.size)
    } else {
      size = Number(updateSize)
    }

    if (updateTime == null) {
      time = Number(nullCase.time)
    } else {
      time = Number(updateTime)
    }



    //after all the above checks, I want my current object to get its values assigned and ready to be posted
    this.body = {
      "hash": updateHash.toString(),
      "height": height,
      "size": size,
      "time": time
    }

    //after the object to post is ready, I want to make the post into the database
    this.http.post(this.url, this.body).subscribe((result) => {
      console.log(result)
    });


  }

但是似乎所有内容都不同步,因为除了检查外,我还得到空对象

1 个答案:

答案 0 :(得分:1)

1)您正在将一个Subscription分配给nullCase,这没有意义。

nullCase = this.http.get(this.url).subscribe(result => {}); // Wrong
this.http.get(this.url).subscribe(result => { nullCase = result });

2)Get是异步的,您需要根据回调函数内部的结果编写代码

// Wrong
this.http.get('url').subscribe(result => { nullCase = result });
this.http.post('url', {}).subscribe(result => { // Something using nullCase });

// Should be
this.http.get('url').subscribe(result => {
  this.http.post('url', {});
});

3)更好的是,您不应该嵌套订阅,而应该使用rxjs运算符:

this.http.get("").pipe(
  switchMap(result => {
    return this.http.post("", {});
  })
).subscribe();