typescript 由于“刚刚评估了下面的值”,无法获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45496171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:47:09  来源:igfitidea点击:

Cannot get the data due to "Value below was evaluated just now"

angulartypescriptionic-frameworkobservable

提问by Victor de Almeida

Well, I spent a lot of time looking for help for this problem but nothing worked for me. I'm getting an Array of Objects from my provider:

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

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

In console, it shows:

在控制台中,它显示:

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

If I try this.produtos.forEach(produto => ...), it does not show me nothing, because the Array is empty. I think it's because the data is get asynchronously and (like the Chrome's console says when I ckick in the iicon) "the value was evaluated just now", but why I can show in html using ngForbut can't get the data inside the .ts file ?

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

回答by DeborahK

It's just a timing issue. When the page first displays, the data is not there so the ngFor does nothing. Later, when the data arrives, the Angular change detection picks up that the data is now available and it updates ... reexecuting the ngFor and it works.

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

You don't show where the forEach is executed in the code ... but my guess is that it is before the data is retrieved. That is why it is empty.

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

Try moving that code to withinthe subscribe.

尝试代码移动到subscribe

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

That way the code won't run until afterthe data is retrieved.

这样,直到检索到数据,代码才会运行。

I tried it in my code like this:

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

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

回答by Sachin Mishra

I have fixed by reassigning the object again after subscription i.e.

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

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

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