Connecting HTML to an AngularFirestore collection using snapshotChanges

In my mobile app, I am using AngularFirestore2v5/rxjs to connect a hybrid Ionicv3/Angularv4 app to a Firestore collection. While binding UI with AngularFirestore.valueChanges works fine, switching to snapshotChanges for retrieving the id is causing some issues. The examples in this thread and video suggest using map and console.log to work with it.

_col: AngularFirestoreCollection<_model>;
_snapshot: any;

constructor(private afs: AngularFirestore) {
  this._col = this.afs.collection('items'); 
  // 'items' refers to the name of the collection in Firestore.
  this._snapshot = this._col.snapshotChanges()
                    .subscribe(actions => {
                      return actions.map(snap => {
                        let id = snap.payload.doc.id;
                        let data = { id, ...snap.payload.doc.data() };
                        console.log(data); 
                        // Output: {id: "Q6YZOzyFPvrfsxwT3uTS", field1: "a thing", field2: "another"}
                        return data;
                      });
                    });

The console log inside subscribe correctly displays the data from the store. However, I'm unsure how to bind this to the UI in an angular manner.

To make the valueChanges examples work, you need to use the async pipe in your UI. But when applied to _snapshot, it gives an error:

Error: InvalidPipeArgument: ‘[object Object]’ for pipe ‘AsyncPipe’ When trying to use the json pipe, it results in: ERROR TypeError: Converting circular structure to JSON This clearly isn't the right approach. So, what should be done instead?

Answer №1

When using the Async pipe, it expects an observable that is not yet subscribed and should return a value. The Async pipe will handle the subscription on its own and output the value.

To implement this, you can use the following code:

this._snapshot = this._col.snapshotChanges()
                .subscribe(actions => {
                  return actions.map(snap => {
                    let id = snap.payload.doc.id;
                    let data = { id, ...snap.payload.doc.data() };
                    console.log(data); //{id: "Q6YZOzyFPvrfsxwT3uTS", field1: "a thing", field2: "another"}

                    // Use data in your HTML
                    this.data=data

                    return data;
                  });
                });

In your HTML:

<div *ngFor="let item of data" ....

Edit 1

this.dataArray=this._col.snapshotChanges()
                .map(actions => {
                  return actions.map(snap => {
                    let id = snap.payload.doc.id;
                    let data = { id, ...snap.payload.doc.data() };
                    return data;
                  })
                })

In your HTML:

<div *ngFor="let item of dataArray | async" ....

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

angular-oauth2-oidc - Issue with missing 'State' and 'Scope' parameters

One crucial requirement set by the identity server is to refrain from including 'state' and 'scope' in the URL. The specified request format is as follows URL?app=xxx&response_type=code&client_id=yyy&state=zzz&redirect_ ...

Angular 2 and Its Multidimensional Arrays

I'm having some trouble understanding Arrays in Typescript ( Angular 2 ). I am looking to create a specific array to send to my API. array = [ cadSocios => true, name => ['name1', 'name2'], part => ['part1', &ap ...

Error: Null is causing an issue and preventing property 'isSkipSelf' from being read in Angular7

While assembling the package for my module, I encountered the following error. TypeError: Cannot read property 'isSkipSelf' of null at ProviderElementContext._getDependency(C:\Users\ravinder\MyProjectName\node_modules\@ ...

What is the best way to merge two interfaces and convert all of their fields to optional properties?

I have two unalterable interfaces: interface Person { name: string; age: number; } interface User { username: string; password: string; } I aim to merge them into a single interface called Player // please, adjust this code accordingly interfac ...

Sending data from Spark to my Angular8 projectLearn how to seamlessly transfer data from your

I am utilizing Spark 2.4.4 and Scala to retrieve data from my MySQL database, and now I am looking to showcase this data in my Angular8 project. Can anyone provide guidance on the process? I have been unable to locate any relevant documentation so far. ...

Ways to dynamically update a Vuetify 3 element's placeholder text?

Here is the code snippet from my component.vue file: <template> <v-text-field name="Foo" :label="$t('foo')" type="text" hint="This is a hint" persistent-hint >& ...

Communication between Angular components

My question is exactly as the title suggests. Let me explain what I need to do. Currently, I have a component widget. Whenever I click on this widget, a modal pops up with several items inside. Each item corresponds to a different section within the main ...

Experimenting with an Angular 2 component using a simulated service

Currently, I am experimenting with testing an Angular2 component that relies on a service. In order to conduct the test effectively, I aim to provide a stubbed service. However, it appears that the test component does not recognize this stubbed service. ...

Navigating to a child route from a parent component in Angular using the navigate method: A step-by-step guide

Here is the code snippet for my HTML routerLink: <a [routerLink]="['create']">Create</a> - it's working just fine. When I try to call the same on a button click, it doesn't work.. navigateTo(page) { this.router.na ...

tips for managing response time in firebase authentication state

I've been facing an issue with my web application in efficiently checking if it is firebase authenticated. The 'auth state object' doesn't seem to be functioning correctly on my template, as the expected sections are not appearing at al ...

Guide to making a second request using an if statement inside an observable

The aim I have a requirement to make two HTTP requests. The first request should always be executed, and the second request should only be made if a certain condition is met. A signal needs to be emitted when: firstvar and secondvar are equal, and only ...

Error in AngularFire2 typings: The property 'take' is not present in the type 'FirebaseObjectObservable<any>'

Recently, I upgraded my ionic app from beta 11 to rc0, which also involved transitioning from typescript 1.8 to version 2. After following the configuration steps for AngularFire2 on the site Getting Started with Ionic 2 RC0, Firebase 3 + AngularFire 2, I ...

Attaching and detaching dynamic views in Angular within an ngFor loop

I'm currently dealing with an issue where I have a list of chat items that are loaded dynamically. When a user clicks on a specific item, I need to open/close a static component/section (such as a reactions menu) right below that particular chat item. ...

Having trouble establishing a connection with mongoose and typescript

When attempting to establish a connection using mongoose, I consistently encounter the errors outlined below. However, if I use MongoClient instead, everything functions as expected. import connectMongo from '../../lib/connectMongo' console.log( ...

Prevent specific dates on Angular Mat Calendar by utilizing Rest API response

I am currently working with the Angular material calendar, specifically the mat-calendar component. My goal is to dynamically disable certain dates in the calendar based on specific values. HTML <mat-calendar [headerComponent]="exampleHeader" [dat ...

Unable to transfer the form value to the service and City value cannot be updated

I am new to the world of Angular and I am attempting to create a basic weather application. However, I am encountering issues when trying to pass the city value from the form on ngSubmit to the API service. I have attempted to use an Emitter Event to trans ...

The error message "window is not defined in Angular Universal" indicates that the window object

While attempting to utilize @nguniversal/express-engine, I encountered an issue in the main.js file after installing and running it. The error message reads: C:\Folder\ssr\dist\ssr\server\main.js:179450 })(window, functio ...

Using decorators in TypeScript, can we define new class attributes?

Here is an example code snippet: function Getter(target: any, key: string): void { let getter = () => this[key]; /* create "foobar" property from "_foobar" */ Object.defineProperty(target, removeUnderscores(key), { get: getter, enumerabl ...

Retrieve a specific attribute from a collection of JSON objects and transfer it to a separate object

Having a JSON object array with various project information: [ {"Project":"Project 1","Domain":"Domain1","Manager":"Manager1"}, {"Project":"Project 2","Domain":&q ...

Exploring TypeScript: Understanding how to define Object types with variable properties names

Having an issue with a React + TypeScript challenge that isn't causing my app to crash, but I still want to resolve this lingering doubt! It's more of a query than a problem! My goal is to set the property names of an object dynamically using va ...