Utilizing Ionic with every Firebase observable

Can someone help me with looping through each object?

I am trying to monitor changes in Firebase, and while it detects if there is a push from Firebase, I am facing issues displaying it in the HTML.

Where am I going wrong?

Thank you!

ping-list.ts


  pingList() {
      this.ping.getPingList()
          .subscribe((data) => {
               this.ping_list = data;
               console.log(this.ping_list);
          });
     }

*note: When I use console.log(this.ping_list), I can see the object printed in the console. If there are changes in the data (manually changed from Firebase console), it will print again, so I assume the observable is working fine.

ping.ts (provider)


getPingList(): Observable<any> {
      return new Observable(observer => {
           firebase.database().ref('pings/_list')
               .orderByValue().limitToLast(10)
               .on('value',
                    (snapshot) => {
                         observer.next(snapshot.val());
                    },
                    (err) => {
                         console.log(err);
                    }
               );
      });
 }

ping-list.html


     <button ion-item *ngFor="let a_ping of ping_list">
           {{ a_ping.title }}
      </button>

The Firebase data looks like this:


"pings" : {
 "_list" : {
  "-KmjxLuZWIE72D_syD73" : {
    "date_updated" : 1497600717098,
    "desc" : "ping server 1",
    "title" : "ping 1"
  },
  "-Kmk0x-3OI0FP-TYxC3W" : {
    "date_updated" : 1497601921866,
    "desc" : "ping server 2",
    "title" : "ping 2"
  }
},

This gives me an error:

Error trying to diff '[object Object]'. Only arrays and iterables are allowed

Is it because Angular's ngFor directive cannot loop over the ping_list directly? Is there a way to convert the object into an array? I tried console.log(this.ping_list.length) but it returned undefined.

Answer №1

It seems like there may be some confusion in your post, but from what I gather console.log(this.ping_list); correctly shows that you received a push notification but the template is not updating.

To ensure the template updates properly, you can explicitly trigger it within Angular's zone.

import { NgZone } from '@angular/core';

@Component({
  ...
})
export class YourPage {

  constructor(private zone:NgZone, ...) {
    ...
  }

  pingList() {
        this.ping.getPingList()
        .subscribe((data) => {
             this.zone.run(() => {
               this.ping_list = data;
               console.log(this.ping_list);
             }
        });
  }

You can find more information about how using ngZone can help in this informative blog post.

Answer №2

Finally figured it out using this method,

 fetchPingData() {
      console.log('ionViewDidLoad PingListPage');
      this.ping.getPingList()
      .subscribe((data) => {
           this.ping_list = [];
           for (var key in data) {
                if (data.hasOwnProperty(key)) {
                     console.log(key + " -> " + data[key]);
                     this.ping_list.push(data[key]);
                }
           }

      });
 }

Answer №3

If you're looking for a solution, consider using Lodash's _.forIn() function.

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

Create a class with additional attributes to support different types of options

I define a set of options represented by strings: export type Category = 'people' | 'projects' | 'topics' | 'tools' An index is declared as follows: interface Entry { ... } type IPostEntryIndex = { [name in Cate ...

Exporting a constant as a default in TypeScript

We are currently developing a TypeScript library that will be published to our private NPM environment. The goal is for this library to be usable in TS, ES6, or ES5 projects. Let's call the npm package foo. The main file of the library serves as an e ...

The 'type' property is not found on the 'never' type

There seems to be a typescript error showing up as Error: Property 'type' does not exist on type 'never' in the following code snippet: export const getSomething = (actionLog: [] | undefined) => { console.info(actionLog[length ...

How can we effectively test arrow functions in unit tests for Angular development?

this.function = () => { -- code statements go here -- } I am looking to write jasmine unit tests in Angular for the function above. Any suggestions on how to achieve this? it("should call service",()=>{ // I want to invoke the arrow funct ...

The error message states that the argument type '(src: Observable<any>) => Observable<any>' cannot be assigned to a parameter of type 'OperatorFunction<Object, any>'

Encountering a typescript error when trying to start the app. Not sure where I'm going wrong. It seems like it could be an issue with the rxjs version, but struggling to find the right solution. Seeing incompatible types on my system and not getting r ...

Retrieve the text content of the <ul> <li> elements following a click on them

Currently, I am able to pass the .innerTXT of any item I click in my list of items. However, when I click on a nested item like statistics -> tests, I want to display the entire path and not just 'tests'. Can someone assist me in resolving this i ...

Angular services do not hold onto data in memory

Working on an app with a date filter and encountering an issue: I am trying to store data in my service, but when I route, the array in the service keeps resetting itself. How can I maintain the data permanently in my service? Below is the code snippet: ...

The rapid execution of code causing an observable race condition

When exporting a CSV file in my code, I encounter a race condition while trying to modify some data before the export. The issue is that the id gets set correctly, but the number only updates after the method is called a second time. I believe the proble ...

Issue with ng-multiselect-dropdown where clearing selected items programmatically does not visually work as expected

Utilizing the ng-multiselect-dropdown, I have encountered an issue where deselecting an option within the object itself clears the selected items visually and in the variable array. However, when programmatically clearing the selectedItems, the variable a ...

Tips for verifying the presence of a value within an array using checkboxes

My firestore database contains a collection named world with a sub-collection called languages I have developed two functions: one to retrieve all documents from the sub-collection languages, and another function to fetch every language if the userUid val ...

What are the steps to update data using Angular?

I am currently working on a project to create a simple webpage that allows users to add values to a database. The database only contains an ID and a value, which should also be displayed on the page. Although my code is functioning correctly and I can suc ...

Using Redux and Typescript to manage user authentication states can help streamline the process of checking whether a user is logged in or out without the need for repetitive checks in the mapStateToProps function

In the process of developing a web application utilizing React & Redux, I am faced with defining two primary "states" - Logged In and Logged Out. To tackle this challenge, I have structured my approach incorporating a union type State = LoggedIn | LoggedO ...

The versions of my npm and node are not compatible, despite using nvm

I have recently started working with node and npm. I need to run a program repository for my job, which requires compatibility with node version 10.13.0 or even 8.11. I attempted to install nvm, but now every time I try to execute any npm command (includ ...

Unable to retrieve real-time data from Firestore using getStaticPaths in Next.js

While fetching data from Firebase Firestore using getStaticProps is successful, I encounter a 404 page when attempting to implement the logic for retrieving details of individual items with getStaticPaths. The current state of my [id].js code appears as fo ...

Is there a user-friendly interface in Typescript for basic dictionaries?

I'm not inquiring about the implementation of a dictionary in Typescript; rather, I'm curious: "Does Typescript provide predefined interfaces for common dictionary scenarios?" For instance: In my project, I require a dictionary with elements of ...

What is the best way to resolve the unusual resolution issue that arises when switching from Next.js 12 to 13

Previously, I created a website using nextjs 12 and now I am looking to rebuild it entirely with nextjs 13. During the upgrade process, I encountered some strange issues. For example, the index page functions properly on my local build but not on Vercel. ...

Angular jsonp.get request was denied despite receiving a status code of 200 indicating success

I have been attempting to access my basic web API created in Jersey, which returns the following data: [ { "id": 1, "name": "Facebook", "userName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f4 ...

How long does it take to delete and recreate a cloudfront distribution using AWS CDK?

I am currently undergoing the process of migrating from the AWS CDK CloudfrontWebDistribution construct to the Distribution Construct. According to the documentation, the CDK will delete and recreate the distribution. I am curious about the total duration ...

Locate and refine the pipeline for converting all elements of an array into JSON format using Angular 2

I am currently working on implementing a search functionality using a custom pipe in Angular. The goal is to be able to search through all strings or columns in a received JSON or array of objects and update the table accordingly. Here is the code snippet ...

Validate multiple email addresses in a single input field, such as adding multiple recipients to the CC field in an email form using

Currently using Angular2 and primeng to create a basic email form with the following input fields: To: Cc: Message: Here is an excerpt of the code from my component class: constructor(private fb: FormBuilder) { this.createForm(); } createForm ...