TypeError: Cannot read property 'url' of undefined

I am trying to fetch data from a REST API using angular2, everything so far is going fine; however, I have a error that shows on the console only when calling {{content.img.url}} it executes fine on the webpage only as it fetch the image url that needs to be fetched and shows the image, but in chrome console it shows:

EXCEPTION: TypeError: Cannot read property ‘url’ of undefined in
[background-image: url(‘{{content[img].url}}’); in HomePage@63:29]

I really don’t have an idea why it shows the error in the console only! any ideas to solve this?

Below you may find the details of what I am actually doing to fetch the data using the REST API, suggestions of improving the code are welcome!

home.html

 <div *ngFor="#content of c1">
 <div class="cards" style="background-image: url('{{content.img.url}}');">
 <div class="txt">{{content.c1Name}}</div></div>
 </div>

home.js

export class HomePage {
static get parameters(){
return [[Http]];
}

constructor(http) {
this.http = http;
this.c1 = null;
//this is a bad way to do it as _defaultOptions is Protected, is there any way to do it better?
this.http._defaultOptions.headers.append('X-Parse-Application-Id', 'appk');
this.http._defaultOptions.headers.append('X-Parse-REST-API-Key', 'apikey');

this.http.get('https://example.com/classes/table').subscribe(data => {
    this.c1 = data.json().results;
});

}

Output of the fetched JSON

0:Object
  createdAt:"2016-01-08T13:55:53.558Z"
  c1Name:"Jack"
  img:Object
     __type:"File"
     name:"tfss-6a8bf-1db8-4545-91e6-18-file.jpg"
     url:"http://files.parsetfss.com/f213b50e-dsdsdas-23fsrfdfd-d/file.jpg"
  objectId:"3mfH4sd23"
  updatedAt:"2016-01-08T17:21:00.678Z"

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

The message tells about content[img].url in your message and I can see that you use content.img.url. It’s really different. I mean the second one accesses the img property of the content object. The first one the property with the name specified into the img variable.

I expect the content[img] returns null, especially if img is null or undefined. Whereas it’s not the case for content.img.

Are you sure not to use the expression content[img].

See this plunkr: http://plnkr.co/edit/IFAuvA36YXelXkUG4HfN?p=preview.

Jason
Guest

I managed to solve the issue by using the Elvis operator (i.e) in my case I used:

{{content.img?.url}}

Hope this helps somebody!