I'm using Angular and I'm trying to access property img of my object, and when I'm doing console.log(..)
of my whole object. Value is there, but when I'm doing console.log(..)
of object's property it said it's null.
console.log("Product:", this.article);
var url = this.article.img;
console.log("Image" , url);
Console:
I don't know how is this possible if this.article.img
; looks like has some value in console.log
. But when I try to access it, it says it's null. How come?
The object isn't rendered immediately. Your img
property has a null
value at logging time but when you open the object in the console, later, it's filled.
You can check that by logging console.log(JSON.stringify(this.article))
.
The most probable reason of your problem is some asynchronous code whose achievement you're not correctly waiting for. As the object is taken from a database as you said, I guess you forget to use the object in the callback (which might be promise based).
Instead of logging:
console.log("Product:", this.article);
var url = this.article.img;
console.log("Image" , url);
try debugging, so that you can inspect the value in real time:
console.log("Product:", this.article);
debugger;
...
Because the browser console works with references in most modern clients:
Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you click it open.
See: https://developer.mozilla.org/en-US/docs/Web/API/Console/log