5: Configurar Firestore

Objetivo

Configurar Firestore en la aplicación para almacenar y recuperar datos en tiempo real.

Configurar Firestore

Abre src/app/app.module.ts y asegúrate de que el módulo AngularFirestoreModule esté importado:

import { AngularFirestoreModule } from '@angular/fire/compat/firestore';

Implementar CRUD Básico

Abre src/app/home/home.page.ts y agrega la lógica para crear, leer, actualizar y eliminar datos en Firestore:

import { Component } from '@angular/core';
import { AngularFirestore } from '@angular/fire/compat/firestore';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  items: any[] = [];
  newItem: string = '';

  constructor(private firestore: AngularFirestore) {
    this.loadItems();
  }

  loadItems() {
    this.firestore.collection('items').snapshotChanges().subscribe(res => {
      this.items = res.map(item => {
        return {
          id: item.payload.doc.id,
          data: item.payload.doc.data()
        };
      });
    });
  }

  addItem() {
    if (this.newItem.trim().length > 0) {
      this.firestore.collection('items').add({ name: this.newItem });
      this.newItem = '';
    }
  }

  deleteItem(id: string) {
    this.firestore.collection('items').doc(id).delete();
  }
}

Editar home.page.html

Abre src/app/home/home.page.html y agrega el siguiente contenido:

<ion-header>
  <ion-toolbar>
    <ion-title>
      Firestore CRUD
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <ion-item>
    <ion-label position="floating">Nuevo Ítem</ion-label>
    <ion-input [(ngModel)]="newItem"></ion-input>
  </ion-item>
  <ion-button expand="full" (click)="addItem()">Agregar</ion-button>
  <ion-list>
    <ion-item *ngFor="let item of items">
      {{ item.data.name }}
      <ion-button slot="end" color="danger" (click)="deleteItem(item.id)">Eliminar</ion-button>
    </ion-item>
  </ion-list>
</ion-content>

Conceptos Básicos

Firestore es una base de datos NoSQL en tiempo real que permite almacenar y sincronizar datos entre clientes y servidores de manera eficiente. El CRUD básico (Create, Read, Update, Delete) permite gestionar datos en Firestore.

Ejercicio

Implementa la funcionalidad CRUD en tu aplicación utilizando Firestore. Verifica que puedas agregar, leer, actualizar y eliminar datos correctamente.