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 ?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With