Pravu
Pravu

Reputation: 608

Get Data In Array

I stuck at get data from array. Bellow is example image array. I want to get data weather icon but I got error core.js:15724 ERROR TypeError: Cannot read property '0' of undefined

enter image description here

This my code

weatherDaily(){
    this.commonService.getWeatherInfoDaily()
    .subscribe(
      (res) => {
        this.daily = res['list'];
        this.icon = res['list']['weather'][0]['icon'];
        console.log(this.icon);


      }
    )
  }

Upvotes: 1

Views: 37

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71891

It's supposed to be:

this.icon = res['list'][0]['weather'][0]['icon'];

It is however advised to use interfaces when getting data from an API. This will give you code hinting, and makes it much easier to refactor if the API changes for some reason:

export interface WeatherListResponse {
  dt: number;
  // ... etc
}

export interface WeatherResponse {
  cod: string;
  message: number;
  cnt: number;
  list: WeatherListResponse[];
}

You can then use the generic typings on the HttpClient to hint the compiler to what response it receives, and you will get an error if you do not use the correct properties:

getWeatherInfoDaily(): Observable<WeatherResponse> {
  return this.http.get<WeatherResponse>(...);
}

weatherDaily() {
  this.commonService.getWeatherInfoDaily().subscribe((res) => {
    this.daily = res.list;
    // this.icon = res.list.weather[0].icon; <-- TypeScript error
    this.icon = res.list[0].weather[0].icon;

    // if you are using the latest typescript, you can use optional chaining:
    this.icon = res.list[0]?.weather[0]?.icon;


    console.log(this.icon);
  })
}

Upvotes: 4

Related Questions