angulartypescriptfirebaseobservablesubscribe

Subscribe to an observable from HttpClient's GET method


I'm learning Angular and the course is outdated. I'm writing a very simple app which shows a list of people created from Persona class which receives the parameters nombre and apellido.

The code is the following:

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(`Datos enviados correctamente: ${response}`),
            error => alert(`Error al enviar los datos: ${error}`)
        );
    }

persona.service.ts:

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

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

  agregarPersona(persona: Persona) {
    this.logginService.enviarMensajeAConsola('agregamos persona:' + 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);
      }
    );
  }

By doing this I receive the error No overload matches this call.

Doing research I found that I should modify the subscription on personas.component.ts as follows:

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

That solved the previous error, however now I get this another error: NG0900: Error trying to diff '[object Object]'. Only arrays and iterables are allowed.

When I do a console.log() of the object that I receive when I subscribe (personas) I can see that it's an object which contains an array (I left you an image of it at the end), but I don't know how to access to this array because when I try to iterate it I also get an error. When trying Object.keys(personas) I get a string with the name of the key and with Objects.values(personas) I get another object.

How can I work with the Persona's objects array that I get from Firebase?

console.log(personas)


Solution

  • The method cargarPersonas() is not returning an Observable<Persona[]>, it's returning and http response object. In order to return the wanted type, you should change it to the following:

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

    this also means you don't need to cast the argument:

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

    An explanation of how it works can be found in this doc