📜  angular firebase crud - Javascript (1)

📅  最后修改于: 2023-12-03 14:39:12.884000             🧑  作者: Mango

Angular Firebase CRUD - JavaScript

Introduction

In this tutorial, we will learn how to perform CRUD (Create, Read, Update, Delete) operations using Angular and Firebase. Angular is a popular JavaScript framework for building web applications, and Firebase is a cloud-based platform for developing mobile and web applications. By integrating Angular with Firebase, we can easily create a real-time database with authentication and perform CRUD operations on the data.

Prerequisites

Before getting started, make sure you have the following:

  1. Basic knowledge of JavaScript, HTML, and CSS.
  2. Node.js and npm (Node Package Manager) installed on your machine.
Step 1: Set up the Angular project

First, let's create a new Angular project using the Angular CLI (Command Line Interface). Open your terminal or command prompt and run the following command:

ng new angular-firebase-crud

This command will generate a new Angular project with the name "angular-firebase-crud". Once the project is created, navigate into the project folder:

cd angular-firebase-crud
Step 2: Install Firebase dependencies

To use Firebase in our Angular project, we need to install the necessary Firebase dependencies. Run the following command to install Firebase and AngularFire:

npm install firebase @angular/fire
Step 3: Set up Firebase project

If you don't have a Firebase account, go to the Firebase website and create a new project. Once you have a Firebase project, navigate to the project dashboard, and click on "Add app". Select the web option (</>) and register your app by providing a name for it.

After registering the app, Firebase will generate a Firebase configuration object. Copy the object contents as we will need it later.

Step 4: Configure Firebase in Angular

Open the src/environments/environment.ts file and add the Firebase configuration object obtained from the previous step:

export const environment = {
  production: false,
  firebase: {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
    appId: "YOUR_APP_ID"
  }
};

Replace the placeholder values with your actual Firebase configuration details.

Step 5: Initialize AngularFireModule

In the src/app/app.module.ts file, import the necessary AngularFire modules and initialize AngularFireModule with the Firebase configuration:

import { AngularFireModule } from '@angular/fire';
import { environment } from '../environments/environment';

@NgModule({
  imports: [
    AngularFireModule.initializeApp(environment.firebase)
  ]
})
export class AppModule { }
Step 6: Create Firebase service

Let's create a Firebase service to handle the CRUD operations. Create a new file src/app/services/firebase.service.ts and add the following code:

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class FirebaseService {
  private itemsCollection: AngularFirestoreCollection<any>;
  items: Observable<any[]>;

  constructor(private afs: AngularFirestore) {
    this.itemsCollection = this.afs.collection<any>('items');
    this.items = this.itemsCollection.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data();
        const id = a.payload.doc.id;
        return { id, ...data };
      }))
    );
  }

  getItems(): Observable<any[]> {
    return this.items;
  }

  addItem(item: any): Promise<any> {
    return this.itemsCollection.add(item);
  }

  updateItem(id: string, item: any): Promise<void> {
    return this.itemsCollection.doc(id).update(item);
  }

  deleteItem(id: string): Promise<void> {
    return this.itemsCollection.doc(id).delete();
  }
}

This service sets up a connection to the "items" collection in Firebase and provides methods to perform CRUD operations.

Step 7: Use the Firebase service in a component

Now let's create a sample component src/app/components/item-list/item-list.component.ts that showcases the CRUD operations. Add the following code to the component:

import { Component, OnInit } from '@angular/core';
import { FirebaseService } from '../../services/firebase.service';

@Component({
  selector: 'app-item-list',
  templateUrl: './item-list.component.html',
  styleUrls: ['./item-list.component.css']
})
export class ItemListComponent implements OnInit {
  items: any[] = [];

  constructor(private firebaseService: FirebaseService) { }

  ngOnInit(): void {
    this.firebaseService.getItems().subscribe(items => {
      this.items = items;
    });
  }

  addItem(): void {
    const newItem = {
      name: 'New Item',
      description: 'This is a new item.'
    };
    this.firebaseService.addItem(newItem);
  }

  updateItem(item: any, newName: string): void {
    const updatedItem = { ...item, name: newName };
    this.firebaseService.updateItem(item.id, updatedItem);
  }

  deleteItem(id: string): void {
    this.firebaseService.deleteItem(id);
  }
}

This component uses the FirebaseService to fetch, add, update, and delete items from the Firebase collection.

Conclusion

In this tutorial, we have learned how to perform CRUD operations using Angular and Firebase. We set up an Angular project, integrated Firebase, created a Firebase service to handle the CRUD operations, and used the service in a sample component. You can now extend this functionality and build powerful web applications with Angular and Firebase!

For more information, refer to the official Angular documentation and Firebase documentation.