Help with Angular 5 Observables.
I want to hide the complexity from the controller; that is to not make it have to subscribe to the observable. Have all the complexity in the service and have it simply return the results/payload to the component. But obviously I'm getting stuck in a timing issue. I feel as if this should be a popular thing/topic, but haven't found the answer. So perhaps I'm going about things wrong?
//in the component.ts
const allColors = this.auth.getColors(); //service call
console.log(allColors); // returns undefined
//in the service.ts
getColors() {
var myColors = "";
var colors = this.http.get<any>('http://localhost/Account/GetColors', httpOptions)
.pipe(catchError(this.handleError));
//
colors.subscribe(
res => {
myColors = res.body;
},
error => {}
);
return myColors;
}
I think you can't do what you wanna do, because until the subscribe in your service doesn't get resolved it won't send anything to the component, in the execution of the component it's undefined cuz the response haven't come yet.
That's why callback functions are invented. The correct way to do it is having the subscribe in your component cuz you want to wait for the response of the service.
Sorry but I cannot use comments yet so I had to make this reply. Hope it helps
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