I'm working on an angular project, I have a situation where making a call to backend using an observable to fetch products.
Here is how the code looks like.
getProducts () : Product[] {
this.http.get<[]>(this.m_baseURL '/products').subscribe(res => {
console.log(res)
this.products = res;
});
return this.products
}
Problem is, the return statement doesn't wait for the above statement to get executed. And in my component, I get an empty array. I checked using console log in both service and component. And it turns out return statement gets executed before observable is done assigning the value.
How do I make it stop until it completes its job, just like async await does. Should I use normal async await instead of observable?
This is my first Angular project, so please pardon me if the question is novice.
CodePudding user response:
You could use an async / await pattern for this, but I recommend against it. Learn how to program asyncronously using Observables.
The service method to load products should return the Observable:
getProducts () : Observabe<Product[]> {
return this.http.get<[]>(this.m_baseURL '/products')
}
The consuming code should subscribe to the Observable and get the data:
myGetProductService.getProducts().subscribe(res => {
console.log(res)
this.products = res;
});
CodePudding user response:
The Angular way of doing things here is to not return a Product[]
, but to return the Observable itself:
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(this.m_baseURL '/products');
}
You then use the async
pipe to subscribe to this Observable, and Angular will automatically display the data.
That's for the case where this is a service method. If you're doing this in a component, the simple answer is: don't. Put this in a service. That's what they're for.
Strongly suggest you try Angular's Tour of Heroes tutorial. They go over this sort of thing.