Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need help data binding with Observables in angular

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.

like image 200
zabros20 Avatar asked Aug 04 '19 23:08

zabros20


2 Answers

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);
like image 194
J K Avatar answered Nov 15 '22 01:11

J K


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.

like image 22
Martin Choraine Avatar answered Nov 14 '22 23:11

Martin Choraine