Sign up for receiving updates from an observable obtained through the GET method of HttpClient

I'm currently studying Angular and the course material I have is outdated. In my project, I am developing a simple application that displays a list of people created from a Persona class with parameters nombre and apellido.

The code snippet is as follows:

data.services.ts:

    cargarPersonas(){
        return this.httpClient.get('https://listado-personas-53faf-default-rtdb.firebaseio.com/personas.json');
    }

    guardarPersonas(personas: Persona[]){
        this.httpClient.put('https://listado-personas-53faf-default-rtdb.firebaseio.com/personas.json', personas).subscribe(
            response => alert(`Data sent successfully: ${response}`),
            error => alert(`Error sending data: ${error}`)
        );
    }

persona.service.ts:

  setPersonas(personas: Persona[]){
    this.personas = personas;
  }

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

  agregarPersona(persona: Persona) {
    this.logginService.enviarMensajeAConsola('Added person:' + persona.nombre);
    if(this.personas == null){
      this.personas = [];
    }
    this.personas.push(persona);
    this.dataService.guardarPersonas(this.personas);
  }

personas.component.ts:

  ngOnInit(): void {

    this.personasService.obtenerPersonas().subscribe(
      (personas: Persona[]) => {
        this.personas = personas;
        this.personasService.setPersonas(personas);
      }
    );
  }

While implementing this part of the code, I encountered an error stating No overload matches this call.

In my investigation, I realized that I needed to modify the subscription in personas.component.ts like so:

this.personasService.obtenerPersonas().subscribe(
      (personas: Object) => {
        this.personas = personas as Persona[];
        this.personasService.setPersonas(personas as Persona[]);
      }
    );

This adjustment resolved the previous error, but now I face another issue:

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

When I perform a console.log() on the object received upon subscription (personas), I observe that it contains an array within an object. However, I am unsure how to access this array since attempting to iterate over it also triggers an error. Utilizing Object.keys(personas) yields a string representing the key name, while Objects.values(personas) returns another object.

How can I effectively work with the array of Persona objects obtained from Firebase?

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

Answer №1

If you are encountering issues with the method cargarPersonas() not returning an Observable<Persona[]>, it may be because it's currently returning an http response object instead. To fix this issue and ensure the correct type is returned, you can update the method as shown below:

    cargarPersonas(){
        return this.httpClient.get<Persona[]>('https://listado-personas-53faf-default-rtdb.firebaseio.com/personas.json');
    }

By making this change, there should be no need to cast the argument in your code anymore. Here's an example of how you can handle the response:

this.personasService.obtenerPersonas().subscribe(
      (personas:Persona[]) => {
        this.personas = personas;
        this.personasService.setPersonas(personas);
      }
    );

To learn more about how this implementation works, you can refer to this documentation.

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

Accessing Facebook in Ionic 2 Release Candidate 0

I'm interested in adding a Facebook login feature to my Ionic 2 app, but I'm unsure of how to proceed. Most tutorials I've come across demonstrate how to do this with Firebase database, while my project is already using MySql. Can someone gu ...

What is the process for making a mask to use with an input?

Is there a way to create a mask for an input using Angular 2? I attempted to use PrimeNG, but the required attribute doesn't seem to work. I also gave angular2-text-mask a try, but it was unsuccessful as well. Any other suggestions? UPDATE: I foun ...

Testing an Angular2 service that employs RxJs subjects through unit testing

Within my application, I developed an AuthService to manage backend service authorization. Utilizing a BehaviorSubject that updates its subscribers, components are notified of new login states. Below is the simplified code snippet: @Injectable() export cl ...

Merging two lists from Firebase using Angularfire 2

I currently have two Firebase List Observables containing data from two different users. Is there a way to merge these two lists into one comprehensive list? Could it be done something like this: this.totalCards = cardsOfUserOne + cardsOfUserTwo; Any he ...

What is the best way to implement multiple templates for a single component?

Is there a way to configure my Home Component based on the user's role? For instance: If the employee is an admin, then the home component should load the template URL designed for admins. Likewise, if the employee is a cashier, then the home compo ...

Angular ForkJoin() Problem Encountered

Hello, I am currently designing a User Interface and I need to display a unique JSON response value for each 'digId'. In the example below, there are 3 incidents and I used forkJoin to access the 3 JSON responses. digId='4149'; ...

Could someone please provide guidance on how to assign a datepicker value to my form using ng-model?

Check out datepicker.ts import { Component, HostListener, ViewChild } from '@angular/core'; import { BsDatepickerDirective } from 'ngx-bootstrap/datepicker'; @Component({ selector: 'demo-date-picker-hide-on-scroll', ...

How to efficiently test a series of HTTP requests in Angular 6

I have developed a new feature that retrieves user information from django rest auth. To achieve this, I need to make 2 separate requests - one for fetching the authentication token and another for obtaining user information. Within the userService servic ...

How can I personalize the ng-bootstrap carousel to fit my needs

I am currently working on customizing the ng-bootstrap Carousel so that each slide comes from the bottom with a specific animation, without any auto-slide change. Additionally, I want to implement a feature where the slide changes on mouse scroll. My proje ...

Enabling and disabling features in Angular 7 based on a click event

Utilizing Angular 7 along with Typescript 3.1.1 Aim The objective is to implement click events that cannot be triggered again until the previous click event is completed, regardless of the outcome. Illustration <div> <span *ngFor="let a of ...

Eliminating an item from an array with the help of React hooks (useState)

I am facing an issue with removing an object from an array without using the "this" keyword. My attempt with updateList(list.slice(list.indexOf(e.target.name, 1))) is only keeping the last item in the array after removal, which is not the desired outcome. ...

Why isn't my Visual Studio updating and refreshing my browser after making changes to the Angular project?

Having added an Angular project and running it successfully with ng serve / npm start, I encountered an issue. After making changes to the project and saving them using ctrl+s or file/all save, the project server did not recompile and the browser did not ...

Tips for efficiently constructing a Docker container using nodejs and TypeScript

Struggling for the past couple of days to get the project running in production, but it keeps throwing different errors. The most recent one (hopefully the last!) is: > rimraf dist && tsc -p tsconfig.build.json tsc-watch/test/fixtures/failing.t ...

Add CSS styling to a particular div element when a button is clicked

I have been working on a new feature that involves highlighting a div in a specific color and changing the mouse pointer to a hand cursor. I successfully achieved this by adding a CSS class: .changePointer:hover { cursor: pointer; background-color ...

"Encountering issues with Firebase deployment related to function-builder and handle-builder while working with TypeScript

I encountered 4 errors while executing firebase deploy with firebase cloud functions. The errors are originating from files that I didn't modify. node_modules/firebase-functions/lib/function-builder.d.ts:64:136 - error TS2707: Generic type 'Req ...

Activate the button exclusively upon meeting the specified condition in Angular

I am facing an issue where the button remains disabled even after the correct condition is met for a certain range of values in a separate input. The main goal is to prevent users from clicking the button if they enter incorrect data in the input field an ...

"An error will be thrown if attempting to add experimental support for decorators when creating a

Attempting to create a new module in an Angular project using the command: ng g module core/employee-applicant --routing=true Results in an exception being thrown for the newly generated module. An error message stating, "Experimental support for decor ...

Can Angular support nesting forms up to two levels deep?

In my Angular project, I am faced with the challenge of nesting a formgroup two levels deep to achieve a specific functionality. Here is the scenario: I have several small formgroups all belonging to a common parentform. However, for a new page, I need to ...

The element 'swiper-container' is not recognized in version 9

Recently upgraded to swiper v9.0.3 and encountered the issue 'swiper-container' is not a recognized element: If 'swiper-container' is an Angular component, ensure it is included in the '@Component.imports' of thi ...

We are currently moving up from NG 12 to NG 16 and encountering an issue with the package "@ng-bootstrap/ng-bootstrap" due to an incompatible peer dependency

When attempting to upgrade from Angular version 12 to version 13, we encountered some dependency errors. Following the instructions at https://update.angular.io/?v=12.0-13.0, we tried running ng update @angular/core@13 @angular/cli@13. We received the fo ...