【发布时间】: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