1

I get the following JSON represantion from a web service

{
   "STAT": {
      "Total": 216,
      "Average": 2.9722222222222223
   },
   "PPRP": {
      "Total": 31494,
      "Average": 19.884390677589384
   }
}

Within my component I have the following code:

  rawOverview: any
  ngOnInit() {
    this.service.getPlcOverview().subscribe(
    data => {
      this.rawOverview = JSON.parse(JSON.stringify(data))
    },
    err => console.error(err),
    () => console.log('done loading foods')
 );
}

How can I access PPRP and STAT with template syntax?

I tried the following:

<table class="table table-dark">
    <thead>
        <tr>
          <th scope="col">Name</th>
          <th scope="col">Tels with acks</th>
        </tr>
      </thead>
  <tbody>
    <tr>
      <th scope="row">PPRP</th>
      <td>{{rawOverview.PPRP?.Average}}</td>
    </tr>
  </tbody>
</table>

but I get an error in the console.

ERROR TypeError: Cannot read property 'PPRP' of undefined

Is it possible to access a JSON object in this way? Or do I have to create known objects which can access the values?

3
  • 3
    Move the question mark, so it's like this: {{rawOverview?.PPRP?.Average}}. Intially, rawOverview will be undefined, so adding the null safe operator will prevent the error Commented May 1, 2018 at 19:47
  • JSON.parse(JSON.stringify(data)) - why? Commented May 1, 2018 at 21:07
  • @tymeJV Because I get an error when I try it directly with data. JSON.parse needs a string representation. But I see now that I can assign data to my member variable directly. Commented May 1, 2018 at 21:12

2 Answers 2

2

At the moment, because rawOverview is set asynchronously, it starts life undefined, which is causing your error.

If you move the question mark, it will perform a null safe check, which will prevent the error

<td>{{rawOverview?.PPRP?.Average}}</td>

More on that here

Sign up to request clarification or add additional context in comments.

Comments

1

Yes you can and should access it like this. in the HTML just do something like this:

<tr>
  <th scope="row">PPRP</th>
  <td>{{rawOverview.PPRP?.Average}}</td>
</tr>
    <tr>
  <th scope="row">STAT</th>
  <td>{{rawOverview.STAT?.Average}}</td>
</tr>

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.