Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 326
Sylvain Avatar asked Jan 20 '26 03:01

Sylvain


2 Answers

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.

like image 77
ahat91 Avatar answered Jan 22 '26 00:01

ahat91


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

  private projectsCollection: AngularFirestoreCollection<any>;
  projects: QueryDocumentSnapshot[];


    this.projectsCollection = this.angularFireStore.collection('projects');

    this.projectsCollection.snapshotChanges().subscribe(data => {
      this.projects = data.map(data => data.payload.doc)
    });

and then I displayed them kind of like this

<ul>
  <li *ngFor="let project of projects">
    {{ project.data() | json }}
    <button (click)="delete(project.ref)">Delete</button>
  </li>
</ul>

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

like image 37
SeanMC Avatar answered Jan 21 '26 23:01

SeanMC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!