1

I just started working on angular 2 and exploring various of its components. I am getting data response to show on html from server in JSON format. In angular 1.x we can directly hold json object in variable and use its directly on html with the use of '.' operator without defining all variables. My question is:

  1. Can we hold json object receive from server through ajax in any variable in component?
  2. If yes, Then how can we use it on HTML without defining each variable available on that json response?


I am trying to implement is similar like showing below.

{
  "data": {
    "usersDetails": [
      {
        "image": "../userimage.jpg",
        "projects": [
          {
            "project_id": "1",
            "name": "test_project",
            "status": "0"
          }
        ],
        "created_on": "1480935474",
        "name": "Test name",
        "id": "10",
        "username": "tester.user"
      }
    ]
  },
  "message": "OK",
  "status": 200
}


In component:

user = response.data.userDetails[0];

In HTML

<tr>
  <td>User name</td>
  <td>{{user.name}}</td>
</tr>
<tr>
  <td>User image</td>
  <td><img src="{{user.image}}"/></td>
</tr>
<tr>
  <td>User username</td>
  <td>{{user.username}}</td>
</tr>
<tr>
...
</tr>

1 Answer 1

3

If you fetch data from the server it is an async call and

user.name throws an exception because Angular tries to bind before the data is available. You can use the safe-navigation operator ?. to prevent that exception

<tr>
  <td>User name</td>
  <td>{{user?.name}}</td>
</tr>
<tr>
  <td>User image</td>
  <td><img src="{{user?.image}}"/></td>
</tr>
<tr>
  <td>User username</td>
  <td>{{user?.username}}</td>
</tr>
<tr>
...
</tr>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, For answer. This thing works. Great!. Is it right way to achieve this or we can use another approach to get perfect results?
You can also use <tr *ngIf="user">, then the whole <tr> won't be rendered until data is != null. It depends on what is more convenient for your use case. You can also use a resolver or guard to preventing navigating to a route (if applicable) until the async call is completed angular.io/docs/ts/latest/guide/router.html#!#resolve-guard
Great! Thank you for your time and answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.