Unable to get the exact value of data while working with angular

66 Views Asked by At

I have a get request where I get data from the server and this is how it looks

 getStreakConfigurations(){
    this.loyaltyPointsService.getStreakConfigurations().subscribe( data => {
      this.streakConfiguration = data
 console.log(this.streakConfiguration,'check')
    }
       )
  }

when I console.log I get

{id: 8, tenantId: null, days: 2, points: 3, tier: 'MID'}

but when I check the typeof streakConfid.id it says undefined

console.log(typeof this.streakConfiguration.id);

why is it undefined and why is it not a number ?

1

There are 1 best solutions below

0
Saidamir On

Let's say you have a service that returns this array of objects (mockDataArr) and single object(mockDataObj):

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';

@Injectable()
export class LoyaltyPointsService {
  constructor() {}

  mockDataArr = [
    { id: 1, tenantId: null, days: 2, points: 3, tier: 'MID' },
    { id: 2, tenantId: null, days: 3, points: 5, tier: 'HIGH' },
  ];

  mockDataObj = { id: 2, tenantId: null, days: 3, points: 5, tier: 'HIGH' };

  getStreakConfigurationsArr(): Observable<any> {
    return of(this.mockDataArr);
  }

  getStreakConfigurationsObj(): Observable<any> {
    return of(this.mockDataObj);
  }
}

And then you are using it on controller like below:

  public streakConfigurationArr: any;
  public streakConfigurationObj: any;

  constructor(private loyaltyPointsService: LoyaltyPointsService) {}

  ngOnInit() {
    this.getConfigurationsArr();
    this.getConfigurationsObj();
  }

  getConfigurationsArr() {
    this.loyaltyPointsService.getStreakConfigurationsArr().subscribe((data) => {
      this.streakConfigurationArr = data;
      console.log(this.streakConfigurationArr);
      console.log(
        'in array of objects id is undefined',
        typeof this.streakConfigurationArr.id
      );
    });
  }

  getConfigurationsObj() {
    this.loyaltyPointsService.getStreakConfigurationsObj().subscribe((data) => {
      this.streakConfigurationObj = data;
      console.log(this.streakConfigurationObj);
      console.log('in object id is number', typeof this.streakConfigurationObj.id);
    });
  }
}

Here is the stackblitz example