Eladerezador
Eladerezador

Reputation: 1301

Angular 9 - Backend with Firebase and Cloud Firestore

For the front end (Angular) have a server and the back end is in Firebase i am using Cloud Firestore.

I tried database realtime, and everything ok, but I want to try Cloud Firestore and its collections.

The problem is the following:

This is the component:

 items: Array<any>;

  constructor(private aboutUsService: AboutUsService) { }

  ngOnInit() {
    this.getData();
  }

  getData() {
    this.aboutUsService.getContent()
    .subscribe(data => {
      this.items = data;
      console.log('items: ',  this.items);
    }, // Bind to view
    err => {
      console.log(err);
    });
  }

This is the service:

  getContent() {
    return this.db.collection('aboutus').snapshotChanges();
  }

At the moment I have a collection in Cloud Firestore:

Cloud Firestore Collection

Rules Cloud Firestore:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

The service responds and returns the following array with an element (this is the content of this.items):

[{…}]
0:
payload: {type: "added", doc: n, oldIndex: -1, newIndex: 0}
type: "added"

These are the headers in the Chrome network tab:

Request URL: http://localhost:4200/aboutus
Request Method: GET
Status Code: 304 Not Modified
Remote Address: 127.0.0.1:4200

But I am not able to find the data of the collection to display it in the front-end (variable this.items).

If I add elements to the collection "aboutus" in the response the array, it corresponds to the elements of the collection, but I don't get to visualize the data.

What could be the problem? Thank you

Upvotes: 1

Views: 771

Answers (1)

Edric
Edric

Reputation: 26740

As what I'd mentioned in my comment from over 2 weeks ago (on 15 May):

You should be using AngularFirestoreCollection.valueChanges, which returns an Observable of the value of the collection while AngularFirestoreCollection.snapshotChanges shows additional metadata on snapshots. For more info, consider viewing the documentation: https://github.com/angular/angularfire/blob/master/docs/firestore/collections.md

As such, you should replace the snapshotChanges call with valueChanges:

getContent() {
  return this.db.collection('aboutus').valueChanges();
}

Upvotes: 1

Related Questions