0

I have a problem creating a client because it doesn't give me the ID because of the error I show in the title.I have tried many ways and it still doesn't work for me.I don't know if it has to do with Firebase, imports or something else.

service.ts:

import { Injectable } from '@angular/core';
import { Cliente } from '../modelo/cliente.modelo';
import { Observable } from 'rxjs';
import { addDoc, collection, doc, Firestore, orderBy } from 'firebase/firestore';
import { collectionData, docData, query } from '@angular/fire/firestore';

@Injectable({
  providedIn: 'root'
})
export class ClienteService {
  clientes: Observable<Cliente[]>;
  private clientesRef: any;

  constructor(private firestore: Firestore) { 
    // Realizamos una consulta para obtener el listado de clientes
    this.clientesRef = collection(this.firestore, 'clientes');
    const consulta = query(this.clientesRef, orderBy('nombre', 'asc'));
    this.clientes = collectionData(consulta,{idField:'id'}) as Observable<Cliente[]>;  **//ON idField is the  ERROR **
  }

  getClientes(): Observable<Cliente[]>{
    return this.clientes;
  }

  agregarCliente(cliente: Cliente){
    return addDoc(this.clientesRef, cliente);
  }

  getCliente(id: string): Observable<Cliente | null> {
    const clienteRefDoc = doc(this.firestore, `clientes/${id}`);
    return docData(clienteRefDoc,{idField: 'id'}) as Observable<Cliente | null>;
  }
  
}

component.ts:

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { Cliente } from '../../modelo/cliente.modelo';
import { ClienteService } from '../../servicios/cliente.service';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FormsModule, NgForm } from '@angular/forms';

@Component({
  selector: 'app-clientes',
  standalone: true,
  imports: [CommonModule, RouterModule, FormsModule],
  templateUrl: './clientes.component.html',
  styleUrls: ['./clientes.component.css']
})
export class ClientesComponent implements OnInit {
  clientes: Cliente[] | null = null;
  cliente: Cliente = {
  
    nombre: '',
    apellido: '',
    email: '',
    saldo: undefined
  };

  @ViewChild('botonCerrar') botonCerrar!: ElementRef;

  constructor(private clienteServicio: ClienteService) { }

  ngOnInit() {
    this.clienteServicio.getClientes().subscribe(clientes => {
      this.clientes = clientes;
    });
  }

  getSaldoTotal(): number {
    return this.clientes?.reduce((total, cliente) => total + (cliente.saldo ?? 0), 0) ?? 0;
  }

  agregar(clienteForm: NgForm) {
    const { value, valid } = clienteForm;
    if (valid) {
      // Agregamos la logica para guardar el cliente
      this.clienteServicio.agregarCliente(value).then(() => {
        // Limpiamos el formulario
        clienteForm.resetForm();
        this.cerrarModal();
      }).catch(error => {
        console.error('Error al agregar cliente:', error);
      });
    }
  }

  private cerrarModal() {
    this.botonCerrar.nativeElement.click();
  }
}

model.ts:

export interface Cliente{
    id? : string;
    nombre?: string;
    apellido?:string;
    email?:string;
    saldo?:number;
}

I tried changing the value of id by deleting the question sign that allows undefined. Also, i tried looking for a way where i do not have to create an element because the problem appears when i create the variable clienteRef, i did not find a way to keep the value for other operations without creating clienteRef

2
  • please share the stacktrace and exact line where the error occours Commented Mar 7 at 16:01
  • Is the last line of the constructor in service.ts. I wrote it next to the line but it might not be seen Commented Mar 8 at 5:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.