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 is used to call a function that captures a specific div and then waits for the capture to be completed before

I'm facing a challenge where I need to handle the capturing of a div using a method called capture() within another method. Take a look at the code snippet below: theimage; // declaring the variable callcapture() { // perform certain actions t ...

No slides are available for display, resulting in the ngx-owl-carousel console message indicating that the carousel will not be re-rendered

I've been attempting to integrate ngx-owl-carousel-o into my Angular 11 application, but I keep encountering the following message in my console: There are no slides to show. As a result, the carousel will not be re-rendered. Unfortunately, nothing ...

Ionic Troubleshoot: Issue with Reading Property

Encountering an error: A TypeError occurs: Cannot Read Property of "username" of Undefined The HTML code responsible for the error is as follows: <ion-content padding style="text-align: center; margin-top: 35px"> <form (ngSubmit)="logFor ...

Easy steps to bring in type definitions from an npm package using Vite

I am currently developing a package with several ts functions that will be utilized by multiple repositories, including mobile and web applications. In our team, we use vite as our primary build tool, which is also integrated into the repository. Below is ...

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

How to delete an item from an object in TypeScript

Can you help with filtering an object in Angular or TypeScript to eliminate objects with empty values, such as removing objects where annualRent === null? Additionally, what method can we use to round a number like 2.833333333333335 to 2.83 and remove the ...

Change TypeScript React calculator button to a different type

I am currently troubleshooting my TypeScript conversion for this calculator application. I defined a type called ButtonProps, but I am uncertain about setting the handleClick or children to anything other than 'any'. Furthermore, ...

Keys preset in TypeScript using keyof

I need a set of predefined keys, but users should not be restricted to only using those keys. type B = { a: string; b: number; } type T = keyof B | string; function someFunc(key: T) {} someFunc(); // key type is `T` In the scenario above, I am lo ...

Having difficulties testing the Angular HTTP interceptor with Karma and Jasmine

Testing an http interceptor has been quite the challenge for me. Despite having my token logged in the console and ensuring that the request URL matches, I still can't figure out why it's not working with the interceptor in place. Interestingly, ...

While working on a project that involves TypeScript, Material-UI, and Formik, I encountered an error that originated from

I recently downloaded a project from the following site: https://codesandbox.io/s/gn692 Upon encountering some errors that I couldn't resolve on my own, I decided to download this project to see how it's implemented. Surprisingly, it runs smoothl ...

List the attributes that have different values

One of the functions I currently have incorporates lodash to compare two objects and determine if they are identical. private checkForChanges(): boolean { if (_.isEqual(this.definitionDetails, this.originalDetails) === true) { return false; ...

Issue: Debug Failure. Invalid expression: import= for internal module references should have been addressed in a previous transformer

While working on my Nest build script, I encountered the following error message: Error Debug Failure. False expression: import= for internal module references should be handled in an earlier transformer. I am having trouble comprehending what this erro ...

New Authentication: The sign-in feature will redirect to /api/auth/error

Currently implementing Google sign-in functionality on my Next.js 13 app using Next-auth. I have utilized the signIn() function as described in the documentation here. However, upon calling the signIn() function, I am unexpectedly redirected to http://loca ...

The displayed number of rows in the paginator selection is inaccurate

My table in Angular Material is displaying the 'Items per page' numbers under the table instead of under the select option element (orange marker). Can someone explain why this is happening? Here is my HTML template: <div class="containe ...

Position the text alongside the thumbnail rather than in the center

In the current setup, my username text is positioned in the center of the view. I want to reconfigure it so that it displays directly to the right of the thumbnail. However, removing the alignItems: 'center', property from the item disrupts the e ...

Retrieving an Observable within an Observable is a feature found in Angular 9

Seeking a solution to return an Observable nested within another Observable. Although I've tried using the pipe and map operators, it doesn't appear to be functioning correctly for me. What could be causing the issue? My development environment ...

Exploring the contrast of utilizing the `new Date()` function compared to Firestore's `new

I am developing a new app and need to calculate the time elapsed between the start and end of a run. When the run starts, I record a timestamp using the new Date() function in Firebase. (I opted for this over firestore fieldValue to avoid conflicts with o ...

Troubleshooting NativeScript 5: Uncovering the iOS Memory Woes of Crashes and Le

Check out this link for more information: https://github.com/NativeScript/NativeScript/issues/6607 Software Stack: NativeScript 5 Angular 7 Demo repository: https://github.com/reposooo/ns-out-of-memory This issue is based on a similar problem i ...

Utilizing localstorage data in angular 2: A comprehensive guide

Is there a way to utilize data stored in localstorage for another component? This is what the localstorage service looks like: localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success, res: res.data })); I am inte ...

Creating a unique theme export from a custom UI library with Material-UI

Currently, I am in the process of developing a unique UI library at my workplace which utilizes Material-UI. This UI library features a custom theme where I have integrated custom company colors into the palette object. While these custom colors work perfe ...