【问题标题】:Can't return the assigned value [duplicate]无法返回分配的值[重复]
【发布时间】:2019-10-05 14:00:46
【问题描述】:

我有这样的功能;

getList() {
    this.http.get(this.rootURL )
    .toPromise().then(res => { this.mimeList = res as Mime[];
                               this.arrayLenght = this.mimeList.length;
    });
    return this.arrayLenght;
  }

在这个函数中,我想返回mimeList 数组的长度。变量arrayLength用于存储长度值,在类体中声明如下;

export class MimeService {
         .
         .
         .
         .
  arrayLenght = 0;
         .
         .
         .
         .
         .
         .
}

当我在 this.http.get(this.rootURL ).toPromise().then 正文中放置 console.log 语句时,它会打印出数组的实际长度。所以这意味着,检索这个数组的长度没有问题。但是,在我调用getList() 函数的另一个类中;

export class AssetListComponent implements OnInit {
             .
             .
             .
             .
             .
             .
ngOnInit() {
  this.service.getList();
  this.serviceCountry.getList();
  this.databaseLength = this.serviceMime.getList();
}
             .
             .
             .
             .
             .
             .
}

返回值是"0",而不是数组的实际长度。当我运行console.log(this.databaseLength) 时,我可以看到这一点。

我哪里错了?我是 Typescript 的新手,很可能这个问题的答案很简单。提前致谢。

【问题讨论】:

  • 异步的东西不是这样工作的。在返回任何值之前,您的 Promise 需要解析。

标签: angular typescript


【解决方案1】:
async getList() {
    const res = await this.http.get(this.rootURL ).toPromise();
    this.mimeList = await res as Mime[];
    this.arrayLenght = this.mimeList.length;
    return this.arrayLenght;
}

像这样改变你的 getList() 函数。你应该等到你的承诺得到解决。在您的其他类中,在调用 getList(); 之前添加 await 关键字;

this.databaseLength = await this.serviceMime.getList();

【讨论】:

  • 我收到以下错误; Type 'Promise<number>' is not assignable to type 'number'
  • 你能检查一下你在哪一行得到这个错误吗?
  • 当我将getList() 的返回值分配给另一个类的变量时发生错误。 this.databaseLength = this.serviceMime.getList();
  • 在你的其他类中 this.databaseLength = await this.serviceMime.getList();这样做。我还编辑了我的答案
猜你喜欢
  • 2021-12-29
  • 1970-01-01
  • 2022-10-02
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
  • 2014-08-26
  • 2014-12-12
  • 2014-07-15
相关资源
最近更新 更多