Is this the correct way to bind data using Observables? if it is, what else is wrong with my code that makes the selectedCourse variable equal undefined?
this.golfDataService
.getGolfData(id)
.subscribe(data => {
this.selectedCourse = data.data
console.log(data.data)
})
setTimeout(function () { console.log(this.selectedCourse) }, 2000);
}
I expect both console.log statements to return the same thing, but only the first console.log returns the data, which is an object with golf course information, but the console.log(this.selectedCourse) returns undefined.
Use arrow function. Then again depending on how fast the getGolfData call is, you 'might' get the value logged. The point it, we shouldn't try to use timers to rely on getting the data, instead develop the code in event driven way.
this.golfDataService
.getGolfData(id)
.subscribe(data => {
this.selectedCourse = data.data;
console.log(data.data);
});
setTimeout(() => console.log(this.selectedCourse), 2000);
I suggest you to not subscribe Observable
in component logic unless you explicitly unsubscribe()
subscriptions.
A better approach (less code, less complexity, best performance) is to use async
pipe provided by Angular.
this.selectedCourse$ = this.golfDataService
.getGolfData(id)
.pipe(
map(res => res.data),
tap(x => console.log(x))
);
Then in template :
<div *ngIf="selectedCourse$ | async as selectedCourse">
Hello {{selectedCourse}}
</div>
This approach has a lot of benefits like cleaner code, avoid memory leak, easy migration to OnPush
change detection strategy and powerful usage of RxJS.
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