1

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]}}°
2
  • 1
    The error is pretty self-explanatory, your temperature variable is undefined. Try doing some console logs when the data comes in to see where your error is Commented Aug 23, 2019 at 13:07
  • First element would be ['temperature'][0] Commented Aug 23, 2019 at 13:11

3 Answers 3

5

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

Comments

2

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]}}

Comments

0

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

Comments

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.