I have a component in my angular5 application called: product-list.component.ts
. In this component, I have a constructor, which calls a REST API.
product.service.ts
getAllProductsFromACategory(categoryName: string): any {
this.http.get('http://localhost:8080/VespaWebshopAPI
/api/Article/Category?categoryName=' + categoryName).
subscribe(data => {
var article: Article = {
id: data[0].id,
name: data[0].name,
articleNr: data[0].articleNr,
stock: data[0].stock,
price: data[0].price,
description: data[0].description
};
return article;
});
product-list.component.ts
public article: Article;
constructor(private route: ActivatedRoute,
private productService: productService) {
//Call rest api
this.article =
this.productService.getAllProductsFromACategory('Bremsen');
}
article.ts
export interface Article {
id : number;
name : string;
articleNr : string;
stock : number;
price : number;
description : string;
}
In my HTML, I want to display some properties of an article. So if I try to run this code in my product-list.component.html file, I get the following error:
{{ article.id }}
Error
ProductListComponent.html:1 ERROR TypeError: Cannot read property 'id' of undefined
at Object.eval [as updateRenderer] (ProductListComponent.html:1)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14727)
at checkAndUpdateView (core.js:13841)
at callViewAction (core.js:14187)
at execComponentViewsAction (core.js:14119)
at checkAndUpdateView (core.js:13842)
at callViewAction (core.js:14187)
at execEmbeddedViewsAction (core.js:14145)
at checkAndUpdateView (core.js:13837)
at callViewAction (core.js:14187)
The REST API works; I tested it. I guess there is just the problem that the data should get loaded first before the HTML page gets displayed. Somewhere else I read that in an ngFor
, I should make use of the | async pipe, but that didn't work for me.
So how do I solve this?