3

I want to print values from a single object in HTML, but it is throwing an error.

{
  "id": "221",
  "user_id": "455",
  "membership_id": "3",
  "is_cemetery": "0",
  "first_name": "tinku",
  "last_name": "tinku",
  "gender": "male",
  "dob": "2019-03-16",
  "i_am": "",
  "looking_for": "",
  "phone": "9876543210",
  "street": "",
  "city": "mohali",
  "state": "",
  "country": "GE",
  "zipcode": "160055",
  "photo": "",
  "description": "test",
  "created_date": "2019-05-27 10:23:46",
  "country_name": "Georgia",
  "image": false,
  "dogs": [{
    "id": "336",
    "user_id": "455",
    "agency_name": "tinkurana99",
    "dog_name": "Tom",
    "training_status": "",
    "selectbreed": "Cross",
    "breed": "261",
    "dog_color": "red",
    "dog_gender": "male",
    "maturity": "Puppy",
    "age_type": "",
    "dog_age": "",
    "age_year": "2",
    "age_month": "2",
    "age_week": "2",
    "eating_habit": "",
    "istrained": "Yes",
    "vaccinated": "yes",
    "description": "Doggy Dating agency",
    "dog_photo": "uploads/5cec705462b13.jpeg",
    "cemetery": "No",
    "start_year": "",
    "end_year": "",
    "cemetery_content": "",
    "iam_status": "4",
    "dog_price": "",
    "status": "active",
    "admin_status": "Approve",
    "created_date": "2019-05-27 10:03:32",
    "breed_name": "Australian Terrier-Akita Inu"
  }]
}

So this object is passed from a TS file:

this.userData = this.response.data;

In the HTML I am accessing the values like this:

{{ userData.city }}

But it is throwing an error that city is undefined. I am using Ionic framework v3 and Angular v5.

3
  • Please provide the code including the part where you fetch the data and the html part where userData.city is contained in Commented Jul 23, 2019 at 9:10
  • 6
    Error is not that city is undefined. Error is cannot read property city OF undefined which means userData is undefined. It happens because you're getting data only after template is instantiated. Use safe navigation operator {{userData?.city}} to work around that. Commented Jul 23, 2019 at 9:12
  • The question is very vague. Show show proper code snippet where we can see at where you are assigning data to the variable. But consider how things work, the comment provided by @ritaj might be the solution. Commented Jul 23, 2019 at 9:16

1 Answer 1

3

Write this:

{{userData?.city}}

Instead of:

{{userData.city}}

? is the safe navigation operator. It checks whether the variable is null or undefined, so that our template won't try to select a property of something falsy.

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

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.