I try to understand .valueChanges() and .subscribe() I use AngularFire2 and Angular5
My code works but I don't understand how it works.
My Component :
ngOnInit() {
this.itemService.getLastUnicorns().subscribe(items => {
this.items = items;
console.log(items);
});
}
console.log give a beautiful array : Array [ {…}, {…} ]
My service :
getLastUnicorns() {
this.items = this.afs.collection('unicorns', ref => ref.limit(2)).valueChanges();
console.log(this.items);
return this.items;
}
console.log give Object { _isScalar: false, source: {…}, operator: {…} }
euh WTF ?
QUESTION: what's happened in the service to give this strange object and how I am able to recover a beautiful array in my component ? Thank you
So when you do .valueChanges() in AFS then it is going to return an observable. What is an Observable?
So to get a value from an Observable you must subscribe to it. So in your component you are subscribing to it so it will log the actual array anytime the value changes. In your service you are literally just logging an observable which looks really weird and does not log like you would expect. If you wanted your service to log an array you could do this:
Hope that helps, let me know if you need any further clarification.
Might not be relevant but please be gentle -I found this question when looking for a way to listen to collection changes and get back document references. I used
and then I displayed them kind of like this
This way I'm able to display data output and also use document references from the same array. So if I use a doc reference to delete from the the collection -it updates the array and thus updates the displayed list all at once