【问题标题】:Cannot get the data due to "Value below was evaluated just now"由于“刚刚评估了以下值”,无法获取数据
【发布时间】:2018-01-11 18:21:20
【问题描述】:

好吧,我花了很多时间寻求解决这个问题的帮助,但对我没有任何帮助。 我从我的提供者那里得到了一个对象数组:

this.encarteProvider.getProdutosEncarte('encarte1').subscribe(prods => {
    this.produtos = prods;
    console.log(this.produtos);
});

在控制台显示:

[]
0: Produto
1: Produto
2: Produto
length: 3
__proto__: Array(0)

如果我尝试this.produtos.forEach(produto => ...),它不会显示任何内容,因为数组是空的。我认为这是因为数据是异步获取的(就像 Chrome 的控制台说,当我在 i 图标中点击时)“刚刚评估了值”,但是为什么我可以使用 ngFor 在 html 中显示但不能获取 .ts 文件中的数据?

【问题讨论】:

  • 你能用模拟 json 创建一个 plunker 来展示这个问题吗? :)

标签: angular typescript ionic-framework observable


【解决方案1】:

这只是时间问题。当页面首次显示时,数据不存在,因此 ngFor 什么也不做。稍后,当数据到达时,Angular 更改检测会发现数据现在可用并且它会更新......重新执行 ngFor 并且它可以工作。

您没有显示代码中 forEach 的执行位置......但我的猜测是它是在检索数据之前。这就是为什么它是空的。

尝试将该代码移动到内subscribe。

this.encarteProvider.getProdutosEncarte('encarte1').subscribe(prods => {
    this.produtos = prods;
    console.log(this.produtos);
    this.produtos.forEach(produto => ...);
});

这样代码在在数据被检索到之后才会运行。

我在我的代码中尝试过这样的:

ngOnInit(): void {
    this._productService.getProducts()
            .subscribe(products => {
                this.products = products;
                this.products.forEach(product => console.log(JSON.stringify(product)));
            },
                error => this.errorMessage = <any>error);
}

【讨论】:

  • 对不起,我的错。 forEach 在 subscribe 内,就像您在示例中所说的那样,但即使如此,数组也是空的。
  • 我刚刚在我的代码中尝试过,它工作正常吗?我在上面的答案中添加了我的代码。
  • 我在这里试过了,控制台什么也没显示:(太奇怪了......我很惊讶,因为我在项目的其他部分一直使用类似的东西,但是在这个页面中,一切都出错了。
  • 我试图以另一种方式做我想做的事(对于this.produtos 中的每个元素,显示属性的值):调用执行forEach 的函数,但是,foreach发疯了,开始无限循环!
  • 我通过在订阅后的最终初始化后再次重新分配对象来解决问题,即 this.productos = this.productos.splice(0,this.productous.length)
【解决方案2】:

我已经通过订阅后再次重新分配对象来修复,即

this.prodoctous = this.prodoctous.splice(0,this.prodoctous.length)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多