angular 5: How do I wait for my service to finish and then proceed to the next task?
@TNII, @Hoang Duc, try say you is that generally a service expose Observables. It's in a ngOnInit in your component when you subscribe to the Observable.
//Simple return a get
getAllProductsFromACategory(categoryName: string): any {
return this.http.get('http://localhost:8080/VespaWebshopAPI
/api/Article/Category?categoryName=' + categoryName)
}
In the component, generally in an ngOnInit when we subscribe to
ngOnInit()
{
productService.getAllProductsFromACategory('Bremsen').
subscribe(data => {
if (data[0])
this.article=data[0];
})
}
the {{article?.id}} wrote in the html is a abreviate way to say: if this.article is defined, show me this.article.id.
check if when in a navigator write http://localhost:8080/VespaWebshopAPI /api/Article/Category?categoryName='Bremsen', give you an array of Articles. Check if the elements of the arrays has properties id,name,etc (or return element with another properties)
In productService.getAllProductsFromACategory()
replace subscribe
with map
so that the method returns Observable<Article>
In constructor
of product-list.component.ts
, subscribe to the Observable<Article>
returned from productService
and set value for this.article
in that
this.productService.getAllProductsFromACategory('Bremsen')
.subscribe((art: Article) => {
this.article = art;
},
(err: any) => console.error(err));
In your html, put an *ngIf="article"
in the surrounding element of your interpolation {{ article.id }}
to prevent it from processing until article
obtains a valid value.