Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 i icon) "the value was evaluated just now", but why I can show in html using ngFor but can't get the data inside the .ts file ?

like image 305
Victor de Almeida Avatar asked Aug 03 '17 23:08

Victor de Almeida


1 Answers

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.

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.

Try moving that code to within the 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 after the 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);
}
like image 134
DeborahK Avatar answered Oct 20 '22 04:10

DeborahK