Reputation: 641
I am filling an array with test data in this example so I know the firebase data isn't to blame.
this.lastMessages = new Array();
ref.limitToLast(1).on("child_added", (snapshot) => {
this.zone.run(() => {
this.lastMessages.push("test");
});
});
console.log(this.lastMessages);
console.log(this.lastMessages[1]);
console.log(this.lastMessages.length);
In this example I just push the value "test" into the lastMessages array to make it easier. Now I have 3 logs on the bottom which gives weird results.
The first one logs as expected:
[]
0: "test"
1: "test"
2: "test"
length: 3
__proto__: Array(0)
The second log returns undefined and the last log gives me 0 back as length. I made sure by pushing values it does not become associative. Now it couldn't be because it is running in zone since the first console log gives me the right representation. What is going on?
Upvotes: 0
Views: 84
Reputation: 71911
This is a combination of expecting aync
to be sync
and the chrome developer tools showing the reference array.
the ref.limitToLast(1).on
makes the whole 'adding' process async, which means that when you log the array there are no elements in it yet, because the async part has not fired yet. Check it by placing a console.log
above the this.lastMessages.push
. You will see that the logging of 'add' is done after the logging of the array
The reason it does show 3 items is because of a browser optimization. Read here for more details
Upvotes: 1