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?