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

Using NgRx to observe state changes in a service instead of relying on an Effect

Is it possible for a service to monitor state changes and make HTTP calls based on the state value without being triggered by an effect (NgRx)? In other words, can a service react to a portion of the store and eliminate the need for an effect to be involve ...

Is there a way to reset the selected value of a specific option in Mat-Select?

Using mat-select, I need to reset the selection for a specific value of mat-select's mat-option. For instance, take a look at this example on StackBlitz In the example, the mat-select has three options; when selecting Canada, it should revert back t ...

The HTTP.GET method seems to be malfunctioning

I'm having some trouble loading an image from a HTTP.GET request into my application. The picture just won't seem to display correctly. Any suggestions on what might be causing this issue? Below is the code I am using: HTML: <ion-view view- ...

Is it possible to track when a user switches to a different component in Angular?

I'm looking to set up a confirmation popup when the user attempts to navigate to a different page. I've come across information about hostListener and canActivate, but I'm not exactly sure how to begin! Any guidance would be greatly apprecia ...

What is the best way to compare two TypeScript object arrays for equality, especially when some objects may have multiple ways to be considered equivalent

Currently, I am in the process of developing a cost function for a game where players are given a set of resources in their hand. The resources can be categorized into different types such as Fire, Air, Water, Earth, Good, Evil, Law, Chaos, and Void. Thes ...

After receiving a BehaviorSubject, the application was paused to handle multiple outcomes

I am trying to implement BehaviorSubject for handling my login user. I have a user BehaviorSubject that returns an observable. get IsAuthenticated() { return this.user.asObservable().pipe(switchMap(res => { if (res != null) { return of(true); } ...

Obtaining data attributes in Angular 8

I'm working with Angular 8 and I came across an issue. In my code snippet, there are two data attributes assigned to a button element, but only one attribute is showing up. Is this a syntax error or a bug? <button [attr.data-popolamento]="all" [a ...

@The value of @Input is consistently undefined

I'm using @Input to pass IDs into a child component, where they are used to filter the data set within that component. <div *ngIf="exerciseLength > 0"> <exercise [course]="Course" [filter-by-exercise-id]=""></exercise> </di ...

Struggling to properly interpret and process the latest data being sent from an Angular single page application (SPA

Currently, I am developing a Single Page Application that utilizes Angular 8 on the frontend and Laravel on the backend. The application involves performing CRUD operations, and specifically when dealing with editing functionality, I encounter an issue. Th ...

Troubleshooting Challenges with Installing Angular 5, Node.js, and N

I currently have Node and NPM installed with the most recent versions. When attempting to install Angular/cli, I encountered an error message stating: angular/cli and npm versions not compatible with current version of node. I am beginning to think that I ...

Emphasize a word in a Typescript text by wrapping it in an HTML tag

I've been experimenting with using HTML tags within TypeScript to highlight specific words in a sentence before displaying the sentence in HTML. Despite searching on StackOverflow for various solutions, I haven't been able to find one that works. ...

Error Detected: An unhandled error occurred, triggering a promise rejection: TypeError: The super expression must be either null or a function in Angular version 6

Upon deploying the application on AWS Elastic Beanstalk, an error has surfaced. While the build and deployment processes were successful, one module is giving a Super Expression error. The other modules are functioning correctly, and everything works fine ...

Overtaking a property in a node_module interface: a guide

I am facing a situation where I need to modify an existing interface property in my custom type declaration file, rather than creating a new one. Despite trying various approaches, such as attempting to omit the property, I have not been successful in ach ...

Supertest and Jest do not allow for sending JSON payloads between requests

Below is the test function I have written: describe("Test to Create a Problem", () => { describe("Create a problem with valid input data", () => { it("Should successfully create a problem", async () => { const ProblemData = { ...

AG-Grid hierarchical data structure

Transitioning from kendo tree list to ag grid tree data grid, I am facing a challenge. My table data is currently formatted as shown below, but ag grid requires data in the form of a string array of nodes in a tree. How can I adapt or customize my existing ...

The callback function `(err: any, data: any) => void` does not share any properties with the type `RequestInit`

Inspired by the tutorial at , I am working on a time-based visualization. I am currently using version "d3": "^5.4.0". Here is the code snippet: d3.json('http://127.0.0.1:5000', function (err, data) { if (err) throw err; // Cre ...

Automatically select the unique item from the list with Angular Material AutoComplete

Our list of document numbers is completely unique, with no duplicates included. I am attempting to implement a feature in Angular Material that automatically selects the unique entry when it is copied and pasted. https://i.stack.imgur.com/70thi.png Curr ...

Encountering the error message "Angular: invalid URL value sanitization" every time I attempt to refer to a folder within

I'm currently working on a project where I need to pull images from my disk into an Angular application using PHP as the backend for file retrieval. <ngb-carousel *ngIf="imageNames" class="carousel-fade"> ...

Complete encapsulation in Angular is essential when developing a custom Angular widget for hosting

I am working on an angular widget that needs to be embedded in multiple sites, but I do not have information about these sites. Unfortunately, using an IFrame is not an option for embedding the widget. Therefore, it is crucial that the widget remains com ...

Is there a way to ensure in TypeScript that a generic type includes a property that implements a particular method?

To better explain my query, let me provide an illustration. Suppose I aim to create a method that accepts three parameters, as shown below: customFilter<T>(values: T[], filterString: string, propName: string) any[] { return values.filter((value) ...