Search code examples
observableangularfire2angular5subscribe

Angular5 what's happened with valuechanges() function ? (angularfire2)


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


Solution

  • So when you do .valueChanges() in AFS then it is going to return an observable. What is an Observable?

    Observables open up a continuous channel of communication in which multiple values of data can be emitted over time.

    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:

    this.items = this.afs.collection('unicorns', ref => ref.limit(2))
         .valueChanges()
         .subscribe(data=>{
             console.log(data);
            })
    

    Hope that helps, let me know if you need any further clarification.