mouchin777
mouchin777

Reputation: 1588

Problem having an async POST into a database

Currently I've the following code, that basically posts the results from a form into a database, but sometimes some fields in the form can be null, so Im forced to check the object before the update and save the variables in order for them to not become null.

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)
    });


  }

But seems that everything is running out of sync, because I get null objects besides of checking

Upvotes: 0

Views: 27

Answers (1)

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10157

1) You are assigning a Subscription to nullCase, that doesn't make sense.

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

2) Get is async, you need to have code dependent on the result inside the callback function

// 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) Even better, you shouldn't be nesting subscriptions, you should use rxjs operators for it:

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

Upvotes: 1

Related Questions