0

I am getting json response from service i wanted to get region_name property value from first block only. Following is my json object.

[
{
    "blogid": 286,
    "post_title": "Family Time 2",
    "post_content": "",
    "post_date": "2017-07-27 06:26:34",
    "imageurl": "/wp-content/Love-market-banner.jpg",
    "region_name": "Asia",
    "cat_name": [
        {
            "term_id": 9,
            "name": "FAMILY TIME",
            "slug": "family-time",               
            "category_description": "this is family time",
            "cat_name": "FAMILY TIME",
            "category_nicename": "family-time",
            "category_parent": 0
        }
    ]
},
{
    "blogid": 285,
    "post_title": "Family Time 1",
    "post_content": "",
    "post_date": "2017-07-27 06:26:09",
    "imageurl": "/wp-content/reykjavik-xlarge.jpg",
    "region_name": "Asia",
    "cat_name": [
        {
            "term_id": 9,
            "name": "FAMILY TIME",
            "slug": "family-time",               
            "category_description": "this is family time",
            "cat_name": "FAMILY TIME",
            "category_nicename": "family-time",
            "category_parent": 0
        }
    ]
}
]

My typescript code is as follows

Blogbyregion(regid: any)
{
    var self = this;

    self.blogapi.BlogsbyRegion(regid).subscribe(
        x => {

            this.Blogbyreg = x;


        });
}

and in html i have used

{{Blogbyreg[0]?.region_name}}

I am getting result but also getting error

ERROR TypeError: Cannot read property '0' of null

3
  • 2
    Either initialize your Blogbyreg field like Blogbyreg = [] or do a null check Commented Jul 27, 2017 at 8:16
  • oh wow it worked. also i was using this.Blogbyreg = null; in ngOnit which was causing problem. Thanks @echonax Commented Jul 27, 2017 at 8:24
  • No problem, I'll provide it as an answer so you can close the issue :-) Commented Jul 27, 2017 at 8:25

1 Answer 1

1

You should either initialize your Blogbyreg field like Blogbyreg = [] or do a null check for it.

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

1 Comment

also worth mentioning could be the seemingly unnecessary use of self even tho it's not part of the question? :)

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.