【问题标题】:How do I return a value after promise is resolved Angular Typescript?承诺解决Angular Typescript后如何返回值?
【发布时间】:2020-04-19 12:33:09
【问题描述】:

当我将一个值插入 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);
    }

【问题讨论】:

    标签: angular typescript asynchronous promise async-await


    【解决方案1】:

    出现问题是因为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);
              }
            );
          }
        });
    
      }
    

    【讨论】:

    • ? getFileCount 不返回 observable 这不起作用,你能检查你的答案吗?
    • @MuhammedAlbarmavi 你的解决方案和我的完全一样,就是复制粘贴。检查您的解决方案。 getFileCount 确实返回一个 observable。
    • 一开始你试图通过使用异步等待来解决这个问题,这就是为什么我提到另一种方式??
    • @MuhammedAlbarmavi 不,我提出了 2 个解决方案,Eduard 做了第 2 个。这就是我删除另一个的原因,但我确信它有效。
    • 也许我没有看到,别担心我会删除我的,我们以后尝试解决他们的问题时不需要混淆其他人?
    猜你喜欢
    • 2019-10-01
    • 1970-01-01
    • 2018-03-15
    • 2018-01-21
    • 1970-01-01
    • 2022-01-18
    • 2016-08-19
    • 2019-06-15
    • 1970-01-01
    相关资源
    最近更新 更多