Ali Ghassan
Ali Ghassan

Reputation: 1180

Angular getting array TypeError: Cannot read property '1' of undefined

I have following JSON struncture:

{
  "daypart": [
    {
      "temperature": [
        45,
        27,
        47
      ]
    }
  ]
}

I am trying to display arrays above from JSON API . l want to display only first element form this array , but am getting the following error

Error: Uncaught (in promise): TypeError: Cannot read property '1' of undefined

Code :

 this.http.get("xxxxxxxx")
      .subscribe(data => {

        let f = data["daypart"][0]

        this.duhok = f

        console.log("duhok" +  this.duhok["temperature"][1])

      })

Html :

    {{duhok.temperature[1]}}°

Upvotes: 1

Views: 582

Answers (3)

Tho.Tra
Tho.Tra

Reputation: 145

If you just want to display the first temperature out of the whole JSON structure you could use the following code. Using the async pipe has the advantage that you don't have to subscribe/unsubscribe the observable manually.

TS:

public getData(): Observable {
  return this.http.get("xxxxxxxx");
}

HTML:

{{(getData() | async)?.daypart[0].temperature[1]}}

Upvotes: 2

Kostas Asargiotakis
Kostas Asargiotakis

Reputation: 144

Maybe its because the data are not resolved when you arrive on that component. You can add a resolver to that component on that route, to make sure that when you get there your data has been reolved. Check this: https://angular.io/api/router/Resolve

Upvotes: 0

Qellson
Qellson

Reputation: 552

I'll take a wild guess here and say that the html is rendered before the request is resolved. Try wrapping the interpolation in a ngIf block

<div *ngIf="duhok">
 {{duhok.temperature[1]}}°
</div>

Upvotes: 5

Related Questions