Having trouble getting undefined values for keys while attempting to retrieve all the data from Firebase DB with Angular

Currently, I have code that is fetching records from the Firebase database using both Angular and Ionic.

The code functions properly, but it does not provide me with the keys for each record. Instead, it returns 'undefined'.

I have researched several online tutorials which suggest that switching from using valueChanges() to snapshotChanges() may solve this issue. However, each tutorial demonstrates a different method of extracting records, leading to discrepancies in version compatibility.

As someone who primarily works in Java, transitioning to the JavaScript realm has presented some challenges.

Please provide guidance on how to rectify this situation.

home.ts

export class HomePage implements OnInit {

    private items$: Item[] = [];

    constructor(private  shoppingListService: ShoppingListService) {
      this.shoppingListService.getShoppingList().valueChanges().subscribe((datas) => {
        datas.forEach(data => {
          console.log(data);

          //data.key is undefined here
          console.log("=>" + data.key + " " + data.name + " " + data.quantity + " " + data.price);
          this.items$.push({key: data.key, name: data.name, quantity: data.quantity, price: data.price});
        })
      }, (err) => {
        console.log("problem:", err);
      });
    }

}

ShoppingListService.ts

@Injectable()
export class ShoppingListService {

  //here 'shopping-list' is the name of the table
  private shoppingListRef = this.db.list<Item>('shopping-list');

  constructor(private db: AngularFireDatabase) {
    this.getShoppingList();
  }

  getShoppingList() {
    return this.shoppingListRef;
  }

}

Item.model.ts

export interface Item {
  key?: string;
  name: string;
  quantity: number;
  price: number
}

package.json

"angularfire2": "^5.1.0",
"firebase": "^5.5.9",
"ionic-angular": "3.9.2",
"ionicons": "3.0.0",
"rxjs": "^6.0.0",
"rxjs-compat": "^6.3.3",

ionic info

Ionic:

   ionic (Ionic CLI)  : 4.4.0 (C:\Users\abc\AppData\Roaming\npm\node_modules\ionic)
   Ionic Framework    : ionic-angular 3.9.2
   @ionic/app-scripts : 3.2.0

System:

   NodeJS : v10.13.0 (C:\nodejs\node.exe)
   npm    : 6.4.1
   OS     : Windows 10

https://i.sstatic.net/n0mB1.png

Answer №1

this.shoppingListService.getShoppingList().snapshotChanges().pipe(map((actions) => {
   actions.map(action => {
      console.log(action.payload.doc.data());
      var data = action.payload.doc.data();
      var id = action.payload.doc.id;
     //data.key is not defined at this point
      console.log("=>" + id + " " + data.name + " " + data.quantity + " " + data.price);
      this.items$.push({key: id, name: data.name, quantity: data.quantity, price: data.price});
    })
  }), catchError((err) => {
    console.log("issue:", err);
  });

please test it and inform me if you encounter any problems. Ensure to import pipe, map, and catchError from rxjs as shown below

import { Observable, of, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

Angular 6 Version

Refer to this guide How to utilize snapshotchanges

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

The TypeScript error "Issue with Type Assertion: 'This expression is not callable Type'...' has no call signatures" occurs when there is a missing semicolon

Here's a simplified version of our original code: const start: number = 10 const end: number = 20 (someElement as HTMLInputElement).setSelectionRange(start, end) We encountered an error with the 20, where a red squiggly line appeared indicating ...

How can I simulate a callback function that was not tested?

Currently experimenting with the method below: startScriptLoad(): void { const documentDefaultView = this.getDocumentDefaultView(); if (documentDefaultView) { const twitterData: ICourseContentElementEmbedTweetWidgetData = this.getTwitterWid ...

Changing an Angular template.html into a PDF document within an Angular 2 application can be achieved by utilizing

Exploring Angular 2 and looking for a way to export my HTML component in Angular 2 to PDF using jspdf. I want to convert dynamically generated tabular HTML into a PDF using jspdf. Below is a snippet of sample code along with a Plunker link: import {Comp ...

Angular 5 is throwing an error that says: "There is a TypeError and it cannot read the property 'nativeElement' because it

Being aware that I may not be the first to inquire about this issue, I find myself working on an Angular 5 application where I need to programmatically open an accordion. Everything seems to function as expected in stackblitz, but unfortunately, I am enco ...

Is there a way to showcase all components on a single page in Angular 2 without needing to bootstrap them in appModule?

Is there a way to showcase all my Angular 2 components on one page without having to bootstrap them individually in AppModule.ts? I'm looking for a solution using router-outlet or parent-child relationships. Any guidance on how to achieve this after s ...

How can I simulate or manipulate the element's scrollHeight and clientHeight in testing scenarios?

In my JavaScript code, I have a function that checks if an HTML paragraph element, 'el', is a certain size by comparing its scrollHeight and clientHeight properties: function isOverflow(element: string): boolean { const el = document.getEleme ...

JavaScript: Transform an Array of Strings into an Array of Objects

Here is an array containing different strings: let myArray : ["AA","BB" , "CC" ...] My goal is to transform it into an array of objects: myArray = [{"id":1 , "value": "AAA"},{"id":2 , "value": "BBB"},{"id":3 , "value": "CCC"}...] I attempted to achiev ...

The information being sent from Angular is not being successfully transmitted to the XAM

Here is my Angular service post method: getUserDetails(username , password) { alert(password); return this.http.post<myData>("http://localhost/test/api/auth.php", { username, password }); } This is the structure of my PHP file: <?php ...

How can we prevent users from changing URLs or accessing pages directly in Angular 7 without using authguard?

Hey there! I am trying to find a way to prevent users from accessing different pages by changing the URL, like in this scenario. Is there a method that can redirect the user back to the same page without using Authguard or any Modules? I have a StackBlit ...

What could be the reason for the failure of running `npm install -g @angular/cli`

https://i.sstatic.net/wsjDI.png Attempting to set up angular/cli through the command prompt, using node.js version 8.1.2 ...

Angular2's use of promises, observables, and Dependency Injection (

If I have a service that looks like this import {Injectable} from 'angular2/core'; @Injectable() export class MyService { search(oSrchParams){ let promise = () => new Promise((resolve, reject) => Meteor.call('mockSe ...

Encountering a 401 Error while integrating Azure App Configuration within an Angular 9 Application

After implementing the library found at https://www.npmjs.com/package/@azure/app-configuration Despite following the setup instructions, I encounter a 401 error whenever I make a request using the AppConfigurationClient. The response headers indicate: ww ...

The number entered will be incorporated into the API URL key value by passing the variable from page.html to services.ts

Recently diving into the world of Ionic, Angular, and Typescript, I've had a burning question. Can the number inputted be added to the API URL as one of the key values? I came across this helpful guide, specifically focusing on key event filtering (wi ...

The call stack size has been exceeded in Next.js, resulting in a RangeError

Currently attempting to deploy my project on vercel.com but encountering an error specifically with 3 pages that have no internal errors. An error occurred while prerendering the page "/applications". For more information, visit: https://nextjs.org/docs/me ...

Executing a series of imported functions from a TypeScript module

I'm developing a program that requires importing multiple functions from a separate file and executing them all to add their return values to an expected output or data transformation. It's part of a larger project where I need these functions to ...

What is the best way to format a string into a specific pattern within an Angular application

In my Angular component, I have 4 fields: customerName, startDate, and startTime. Additionally, I have a fourth field that is a textarea where the user can see the message that will be sent via email or SMS. Within my component, I have defined a string as ...

DiscoverField Component with Button Functionality and Checkbox Dilemma

I'm working with Vue 3, Vuetify, and TypeScript for my searchField component. Inside, I have two buttons: FreeItemMaster and PatternMaster. Clicking on these buttons should change their background color and display respective content below them. Howev ...

Accessing elements in a FormArray using formControl along with a personalized iteration

Currently, I have dynamic input fields that I want to incorporate into my form group. Here is the current setup: <div class="services" *ngFor="let section of sections"> <p> <mat-form-field> <mat-label&g ...

Having trouble accessing store state in Angular with NGXS

In the parent component, I am dispatching an action and hoping to receive the dispatched array in the child component. To achieve this, I have implemented the following code: export class ListComponent implements OnInit { @Select(ProductState.getProductD ...

Tips for reactivating getStaticProps following an update:

For a personal project centered around an online shopping platform, I am working on managing the products page. I'm currently attempting to refresh the list of products after deleting one. My current setup involves using Next.JS in conjunction with Fi ...