1

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);


      }
    )
  }

1 Answer 1

4

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);
  })
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much brother for help and advice
@Pravu you're welcome. I've updated my answer with a bit more detail
Where should I add interface..In component or in service?
@Pravu you can create a separate folder with specific interfaces. This way, if you import this interface somewhere else, it's not also importing the component or service, and prevents circular dependencies

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.