Chartjs-TS how can I use a class variable inside method?

2👍

console.log('Labels in: ' + this.stats4Graphs.label); is undefined because the calling for this.profileService.getEngagement('UC__8h96Jwsaptaqh227Q9gg') is asynchronous, so it wasn’t finished yet.

The correct way is to put the statement inside the subscribe

this.profileService.getEngagement('UC__8h96Jwsaptaqh227Q9gg')
  .subscribe(stats4Graphs => {
    this.stats4Graphs = stats4Graphs;

    console.log('Labels in engagement: ' + this.stats4Graphs.label);
    this.labels = this.stats4Graphs.axisLabels as any;
  });

Hope it helps

0👍

You’re console.loging outside of the subscription. Since it looks like the getEngagement() method of the service returns an Observable, all that you need to do is either set your values inside the subscription, or set the stats4Graphs class prop to an Observable<Stats4Graphs> and use an async pipe within your template, like this:

stats4Graph: Observable<Stats4Graph>;

ngOnInit() {
  this.stats4Graph = this.profileService.getEngagement('UC__8h96Jwsaptaqh227Q9gg');
}
<div *ngIf="stats4Graph | async; let graph">
  <!-- now you can use `graph` as your value of the Observable -->
</div>

With this method, you don’t have to actively subscribe to the getEngagement method of the service, and the async pipe automatically handles unsubscribing after your component gets destroyed.

Leave a comment