首页 > 解决方案 > 如何从承诺响应中获取价值并将其分配给 Ionic v3 中数组中的每个对象属性

问题描述

尝试 1:我尝试使用以下函数获取数据。由于它是异步的,因此无法从此函数中获取值。

for (var i = 0; i < this.items.length; i++) {
    let newitems: any = this.items;
    this.restapi.getPendingOrdersCount(this.items[i].store._id, this.user._id).then(data => {
        this.result = data;
        console.log(this.result);
        //able to get the data here
    });

    //Unable to get the data here. 
    newitems[i].pendingCount = this.result;
    console.log("result", this.result);
}

尝试 2:我在上面的函数中添加了额外的变量并且确实返回了。现在我可以在这里获取这些数据,但它不是值,它是一个区域值 => t {__zone_symbol__state: null, __zone_symbol__value: Array(0)}

let newitems: any = this.items;
for (var i = 0; i < this.items.length; i++) {
    var response = this.restService.getPendingOrdersCount(this.items[i].store._id, this.user._id).then(data => {
        this.result = data;
        //console.log(this.result);
        return response;
    });
    //able to get result here but its not value, its a zone value
    newitems[i].pendingCount = this.result;
    console.log("response", response);
}

任何人都可以帮助我更正上述功能,以便我可以重用承诺值。

标签: javascriptangulartypescriptionic-frameworkionic3

解决方案


您正在使用异步调用,getPendingOrdersCount所以在.then执行 之前console.log("response",response);将被执行,这就是为什么它没有在外部提供数据.then

您可以调用dislayResult函数 from.then以获取外部数据,如下所示。

this.restapi.getPendingOrdersCount(this.items[i].store._id, this.user._id).then(data => {
  this.result = data;
  console.log(this.result);
  //able to get the data here
  
  displayResult();
});

displayResult() {
   console.log(this.result);
}

推荐阅读