Home > Mobile >  Angular Get method returns an Undefined instead of object
Angular Get method returns an Undefined instead of object

Time:07-09

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]

CodePudding user response:

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>

CodePudding user response:

rather than using any type create a specific object return type as generic so the error gets resolved !

  • Related