Angular's HttpClient.get method seems to have trouble retrieving real-time data from a Firebase database

I have been debugging and I suspect that the error lies in this part of the code. The DataService class's cargarPersonas function returns an Observable object, but I am struggling to understand how to properly retrieve the database data and display it on the web:

 ngOnInit(): void {
        this.personaService.obtenerPersonas()
        .subscribe({
          complete: () => (personas: Persona[]) => {
              this.personas = personas;
              this.personaService.setPersonas(personas);   
          }
      });
      };

This is what my database looks like in terms of data:

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

Here is my Personas.component.ts class:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Persona } from '../persona.model';
import { PersonasService } from '../personas.service';

@Component({
  selector: 'app-personas',
  templateUrl: './personas.component.html',
  styleUrls: ['./personas.component.css']
})
export class PersonasComponent implements OnInit{
  personas: Persona[] = [];

  constructor(
    private personaService: PersonasService,
    private router:Router
  ) { }
  
  ngOnInit(): void {
    this.personaService.obtenerPersonas()
    .subscribe({
      complete: () => (personas: Persona[]) => {
          this.personas = personas;
          this.personaService.setPersonas(personas);   
      }
  });
  };

  agregar(){
    this.router.navigate(['personas/agregar']);
  }
}

This is my Data.services.ts class:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Persona } from './persona.model';

@Injectable()
export class DataServices{

   constructor(private httpClient: HttpClient){}

    cargarPersonas(){
        return this.httpClient.get('https://listado-personas-4f1c0-default-rtdb.europe-west1.firebasedatabase.app/datos.json');
    }

   //Guardar personas
   guardarPersonas(personas:Persona[]){
        this.httpClient.put('https://listado-personas-4f1c0-default-rtdb.europe-west1.firebasedatabase.app/datos.json',personas)
        .subscribe({
            complete: () => { console.log("Saving People: " + Response) }, // completeHandler
            error: () => { console.log("Error saving people: "+ Error) },    // errorHandler 
        });
   }
}

This is my Personas.services.ts class:

import { LoggingService } from "./LogginService.service";
import { Persona } from "./persona.model";
import { EventEmitter, Injectable } from '@angular/core';
import { DataServices } from "./data.services";

@Injectable()
export class PersonasService{
    personas: Persona[] = [];


    saludar = new EventEmitter<number>();

    constructor(private logginService: LoggingService, private dataService:DataServices){}
    
    setPersonas(personas:Persona[]){
        this.personas = personas;
    }

    obtenerPersonas(){
        return this.dataService.cargarPersonas();
    }

    agregarPersona(persona: Persona){
        this.logginService.enviaMensajeAConsola("agregamos persona: " + persona.nombre);
        if(this.personas == null)
        {
            this.personas = [];
        }
        this.personas.push(persona);
        this.dataService.guardarPersonas(this.personas);
    }

    encontrarPersona(index:number){
        let persona: Persona = this.personas[index];
        return persona;
    }

    modificarPersona(index:number, persona:Persona){
        let persona1 = this.personas[index];
        persona1.nombre = persona.nombre;
        persona1.apellido = persona.apellido;
    }

    eliminarPersona(index:number){
        this.personas.splice(index,1);
    }
}

This is my personas.component.html:

<div style="text-align: center;">
    <button style="cursor:pointer" (click)="agregar()">+</button>

</div>

<div class="box">
    <app-persona
      *ngFor="let personaElemento of personas; let i = index"
      [persona] = "personaElemento"
      [indice] = "i" 
    >
    </app-persona>
  </div>
  
<router-outlet></router-outlet>

Edited: attempting to use Next:

Using next doesn't execute the two statements inside the arrow function.

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

Answer №1

In my response, I suggested using the next observer instead of the complete observer. The next observer returns the values whereas the completed observer only signals that the observable has finished. Additionally, there are two functions currently being used, but the first one lacks any parameters, resulting in the absence of receiving the value.

By making the switch to the next subscription and eliminating the initial arrow function, you can address your issues effectively.

this.personaService.obtenerPersonas().subscribe({
  next: (personas: Persona[]) => {
  // utilize the personas data
}

You can find a simple Stackblitz project here that mirrors your code structure.

Answer №2

After some trial and error, I was able to find the solution to my query using the following code snippet:

  ngOnInit(): void {
    this.personaService.obtenerPersonas()
    .subscribe({
      next: (item) => { 
          console.log("Saving Persons: " + item); 
          this.personas = item as Persona[];
          this.personaService.setPersonas(this.personas);  
      },
      error: () => { console.log("Error saving persons: "+ Error) }, 
      complete: () => { console.log("Successful completion of saving persons")}   // errorHandler 
     });
  };

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

What could be causing the HTTP response Array length in Angular to be undefined?

Currently, I am facing an issue while retrieving lobby data from a Spring Boot API to display it in my Angular frontend. After fetching the data and mapping it into an object array, I encountered a problem where the length of the array turned out to be und ...

Employing a provider within a different provider and reciprocally intertwining their functions

I'm currently facing an issue with two providers, which I have injected through the constructor. Here's the code for my user-data.ts file: @Injectable() export class UserDataProvider { constructor(private apiService: ApiServiceProvider) { ...

Angular 4, Trouble: Unable to resolve parameters for StateObservable: (?)

I've been working on writing unit tests for one of my services but keep encountering an error: "Can't resolve all parameters for StateObservable: (?)". As a result, my test is failing. Can someone please help me identify and fix the issue? Here& ...

Issue occurred while trying to render a React component with Typescript and WebPack

I am in the process of creating a basic React component that simply displays a page saying Hello. However, I'm encountering an error in my console. My compiler of choice is TypeScript. To set up my project, I am following this guide: https://github.co ...

Angular: Displaying Input Elements Based on Checkbox Status

I am trying to use Angular's ng-if directive to display an input element when a checkbox is checked. I also want to be able to display multiple input elements if multiple checkboxes are checked, as I need to enter the quantity for each item. However, ...

Struggles with updating app.component.ts in both @angular/router and nativescript-angular/router versions

I have been attempting to update my NativeScript application, and I am facing challenges with the new routing system introduced in the latest Angular upgrade. In my package.json file, my dependency was: "@angular/router": "3.0.0-beta.2" After the upg ...

Angular threw an error saying: "Template parse errors: is not a recognized element"

I am attempting to utilize babel standalone within a react application to transpile Angular TypeScript. The transpiling process seems to be successful, however, I encounter an error when trying to import a component and use its selector within the template ...

What is the best way to share type definitions between a frontend and a Golang backend application?

I utilized typescript for both the frontend (Angular) and backend (Express). To ensure type definitions are shared, I created a file called shared-type-file.ts. interface Kid{ name: string; age: number; } By then running npm install in both the front ...

"Utilize ngclass to set CSS classes based on enum string values

Is there a way to directly call an element in Angular when using an enum to organize component styles? Instead of writing multiple ng class expressions or dynamically passing them to the element call. button-types.ts export enum ButtonTypes { Primary ...

Creating a double-layered donut chart with Chart.js

I'm attempting to create a unique pie chart that illustrates an array of countries on the first level and their respective cities on the second level. After modifying the data in a JSON file to align with my goal, it doesn't seem to be working a ...

Cached images do not trigger the OnLoad event

Is there a way to monitor the load event of my images? Here's my current approach. export const Picture: FC<PictureProps> = ({ src, imgCls, picCls, lazy, alt: initialAlt, onLoad, onClick, style }) => { const alt = useMemo(() => initial ...

Issue with MEAN app: unable to retrieve response from GET request

FETCH The fetch request is being made but no data is returned. There are no errors, just the fetch request repeating itself. app.get('/:shortUrl',async (req,res)=>{ try{ const shortUrl = await shorturl.findOne({ short: req.params.sh ...

Show a notification if the search bar returns no results

I am facing an issue with my search functionality. When a user searches for something not in the list, an error message should be displayed. However, in my case, if I search for "panadol" in my list, it displays the list containing that word and shows an e ...

Show a component on click event in Angular 4

Looking for a solution to create an event on a button click that triggers another component? When clicked again, the component should be reduced with a part always remaining visible. While I am currently using [ngClass]='hidden' within the same c ...

Frozen objects in Typescript 2 behave in a variety of ways depending on their shape

Let's say I'm working with an object whose inner structure is unknown to me because I didn't create it. For instance, I have a reference to an object called attributes that contains HTML attributes. I then made a shallow copy of it and froze ...

Check the type of the indexed value

I need help with a standard interface: interface IProps<T> { item: T; key: keyof T; } Is there a way to guarantee that item[key] is either a string or number so it can be used as an index for Record<string | number, string>? My codeba ...

Mastering the Use of *ngIf with *ngFor: Best Practices for Proper Implementation

Can someone help me rewrite the combination of *ngIF and *ngFor below? I understand that my issue may be similar to others, but please know that this is different. Everything seems to be working fine. The only problem I'm facing is that the color of ...

I continue to encounter the same error while attempting to deliver data to this form

Encountering an error that says: TypeError: Cannot read properties of null (reading 'persist') useEffect(() => { if (edit) { console.log(item) setValues(item!); } document.body.style.overflow = showModal ? "hidden ...

How can we achieve a seamless fade transition effect between images in Ionic 2?

My search for Ionic 2 animations led me to some options, but none of them quite fit what I was looking for. I have a specific animation in mind - a "fade" effect between images. For example, I have a set of 5 images and I want each image to fade into the ...

ERROR UnhandledTypeError: Unable to access attributes of null (attempting to retrieve 'pipe')

When I include "{ observe: 'response' }" in my request, why do I encounter an error (ERROR TypeError: Cannot read properties of undefined (reading 'pipe'))? This is to retrieve all headers. let answer = this.http.post<ResponseLog ...