承诺解决后,我该如何返回值Angular Typescript?

时间:2019-12-30 20:08:26

标签: angular typescript asynchronous promise async-await

当我将值插入SQL数据库时,我正在使用Angular和Typescript进行验证,它会检查该值是否已在数据库表中。我从ASP .NET CORE API收到响应,如果表数据库服务器中已存在该值,则将返回 true

响应就是这样:

true

例如,我在数据库表中已经有值“ 1”,那么我尝试插入值“ 1”,但是它将插入到表中,当我再次尝试插入值时,它将停止并且不会让我插入它。如果刷新页面,即使数据库表中的值> 10大于“ 1”,也会发生相同的过程。我可以使用什么来解决此问题?如何解决?

FileCount:boolean;
getFileCount() {
        this.http.get<boolean>(this.BaseURL + '/Count/File?Name=' + this.formData.Name)
        .subscribe(
            result => {
                 this.FileCount = result;
                 console.log(this.FileCount);
            }
        );
    }
insertRecord(form: NgForm) {
    this.getFileCount();
        if (this.FileCount == true) {
            this.toastr.warning('Submitted failed', 'There is another file with the name: "' + this.formData.Name + '"');
        }
        else {
            this.postFile().subscribe(
                res => {
                    this.toastr.success('Submitted successfully', 'File Creation Complete');
                    this.refreshList();
                },
                (err) => {
                    console.log(err);
                }
            );
        }
    }
postFile() {
        return this.http.post(this.BaseURL + '/File', this.formData);
    }

1 个答案:

答案 0 :(得分:2)

发生此问题是因为对this.getFileCount()方法的调用是异步运行的,也就是说,它不等待答案,并且过程继续进行,因此您必须等待其响应。

尝试一下:

  getFileCount() {
    return this.http.get<boolean>(this.BaseURL + '/Count/File?Name=' + this.formData.Name);
  }

  insertRecord(form: NgForm) {
    this.getFileCount().subscribe(result => {
      this.FileCount = result;
      console.log(this.FileCount);

      if (this.FileCount == true) {
        this.toastr.warning('Submitted failed', 'There is another file with the name: "' + this.formData.Name + '"');
      }
      else {
        this.postFile().subscribe(
          res => {
            this.toastr.success('Submitted successfully', 'File Creation Complete');
            this.refreshList();
          },
          (err) => {
            console.log(err);
          }
        );
      }
    });

  }