Проблема с асинхронным POST в базе данных - PullRequest
0 голосов
/ 08 мая 2019

В настоящее время у меня есть следующий код, который в основном отправляет результаты из формы в базу данных, но иногда некоторые поля в форме могут быть нулевыми, поэтому я вынужден проверить объект перед обновлением и сохранить переменные в порядке чтобы они не стали нулевыми.

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 Ответ

1 голос
/ 08 мая 2019

1) Вы назначаете подписку на nullCase, что не имеет смысла.

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

2) Get is async, вам нужно, чтобы код зависел от результата внутри функции обратного вызова

// 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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...