0

I am an Angular beginner and I've made a service and made all the set up so that the Get method works on a JSON file and it worked! but the problem is whenever I want to access to the data inside the JSON file it tells me that it is undefined, and I want to use it as an object in the ts file. It works when using data biding like this {{stats | JSON}}, but I couldn't use it in the TS. can I convert this 'undefined' to a simple object?

stats: any;

constructor(private statsData: StatDataService) {
    this.statsData.GetEmbedded().subscribe((data: any) => {
      this.stats = data;
    });
  }

`

enter image description here

for example I can't use stats.preOrders[0]

3
  • 1
    Can you please add the html's view too? It seems you are trying to access this data when is not available. Commented Jul 8, 2022 at 9:40
  • As already noted, your data is not going to be accessible right away, because GetEmbedded() returns an asynchronous observable, which means this.stats is going to be undefined until the observable completes. Commented Jul 8, 2022 at 9:49
  • what should I do then Please? Commented Jul 8, 2022 at 9:55

1 Answer 1

0

To better understand the situation, let's create an example.

example.component.ts

interface Statistics {
    median: number;
    average: number;
}

export class Example {

    // stats is undefined until GetEmbedded() fires
    stats?: Statistics;

    constructor(private statsData: StatDataService) {
        this.statsData.GetEmbedded().subscribe((stats: Statistics) => {
            this.stats = stats;
        });
      }
}



example.component.html

<div>The median is: {{ stats.median }}</div>

Why will this example result in an error? Your variable stats initially is undefined, so it will not have any properties. GetEmbedded() will take some milliseconds to fire but in the same time, the template already tries to access stats.median.

One option to solve this problem would be to check if the variable stats is not undefined and if it is not, access the properties you need.

example.component.html

<div *ngIf="stats">The median is: {{ stats.median }}</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.