简体   繁体   中英

HttpClient.get doesn't get data from database realtime firebase in Angular

I am stayed debbugin and I think the error is in this part of code, my class DataService function cargarPersonas returns an Observable object but I don't know how learn this well and put the database data in the web:

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

This is my database contains data:

在此处输入图像描述

This is my class Personas.component.ts

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 class Data.services.ts

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("Guardar Personas: " + Response) }, // completeHandler
            error: () => { console.log("Error guardar personas: "+ Error) },    // errorHandler 
        });
   }
}

This is my class personas.services.ts:

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: trying to Next:

Trying it with next does not execute the two statements inside the arrow function

在此处输入图像描述

As mentioned in my comment, instead of the complete observer use the next observer. The next observer returns the values , where the completed observer only indicates that the observable has completed. Secondly there are currently two functions, but the first does not have any parameters, so you are not receiving the value.

Changing the subscription to next and removing the first arrow function, resolves your problems.

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

Here is a simple Stackblitz project which tries to imitate your structure.

Finally, I solve my question with this code:

  ngOnInit(): void {
    this.personaService.obtenerPersonas()
    .subscribe({
      next: (item) => { 
          console.log("Guardar Personas: " + item); 
          this.personas = item as Persona[];
          this.personaService.setPersonas(this.personas);  
      },
      error: () => { console.log("Error guardar personas: "+ Error) }, 
      complete: () => { console.log("Guardar Personas se ha completado")}   // errorHandler 
    });
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM