简体   繁体   中英

TS how can I use a class variable inside method?

This has been driving me insane. I know it must be something really stupid that I'm missing, but after perusing the forum and furiously searching with google for half a day, I've given up! Please help. This is my first app with Angular and it seems that I'm not great at it.

I have a class var stats4Graphs that I receive from a service in .net core 3.1. I know the service works because when I use stats4Graphs in the html portion of the component it correctly displays the data. However when I retrieve the data within the function that calls the service I am unable to use the variable, not even for a trivial thing like: console.log('Labels in: ' + this.stats4Graphs.label); , as the console shows me "Labels in: undefined" I don't know what else to do.

Here is my model for stats4Graphs

    export class Stats4Graphs {
    axisLabels: string[] = [];
    label: string;
    points: number[] = [];
}

I don't know if I need to initialize the arrays here or not, it was just one of my desperate attemps to make this work.

Here is my component.ts

import { Component, OnInit } from '@angular/core';
import { Stats4Graphs } from 'src/app/shared/models/stats4-graphs.model';
import { ProfileService } from '../profile.service';

@Component({
  selector: 'app-engagement-chart',
  templateUrl: './engagement-chart.component.html',
  styleUrls: ['./engagement-chart.component.css']
})
export class EngagementChartComponent implements OnInit {  

  public stats4Graphs: Stats4Graphs = new Stats4Graphs();

  // ADD CHART OPTIONS. 
  chartOptions = {
    responsive: true    // THIS WILL MAKE THE CHART RESPONSIVE (VISIBLE IN ANY DEVICE).
  }

  labels =  [];

  // STATIC DATA FOR THE CHART IN JSON FORMAT.
  chartData = [
    {
      label: '',
      data: [] 
    }
  ];

  // CHART COLOR.
  colors = [
    { // 1st Year.
      backgroundColor: 'rgba(77,83,96,0)',
      borderColor: 'rgba(77,83,96,0.2)',
      borderWidth : 2
    }
  ]

  // CHART CLICK EVENT.
  onChartClick(event) {
    console.log(event);
  }
  constructor(private profileService: ProfileService) { }

  ngOnInit() {
    this.profileService.getEngagement('UC__8h96Jwsaptaqh227Q9gg')
    .subscribe(stats4Graphs => {
      this.stats4Graphs = stats4Graphs;
    });
    //this.chartData = this.stats.points as any [];
    //this.chartData = this.stats.label as any;
    console.log('Labels in engagement: ' + this.stats4Graphs.label);
    this.labels = this.stats4Graphs.axisLabels as any;
  }

}

As you can see what I'm trying to do is a line chart (using Chart.js and ng2-charts) that will display the data contained in stats4Graphs I also don't have the slightest idea on how to put the data from stats4Graphs.points and stats4Graphs.label into chartData If you can help me with that it will be great as well.

But now, how do I know that the service actually works? Because I can use it in the component.html and it shows the values that came from the service.

<p>{{ stats4Graphs.label }}
        <br />
        {{ stats4Graphs.axisLabels }}
        <br />
        {{ stats4Graphs.points }}
    </p>

Thanks in advance for all your help

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

You're console.log ing 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM