How to Store, Update, Delete, and Retrieve Data From a Firebase Database Using Angular

Firebase is a platform that gives you with a large number of companies to help with constructing and scaling an software. A few of these options embrace internet hosting companies, knowledge storage, and the flexibility to trace knowledge analytics.

This tutorial focuses primarily on how one can create and add knowledge to a Firebase database, and how one can carry out create, learn, write, and delete operations to the database from an area Angular software.

Create and Add Knowledge to a Firebase Database

Assuming you have already got an Angular software arrange and operating regionally, it would should be linked to a Firebase database with a purpose to retailer and entry knowledge. If you’re not accustomed to Angular, you may learn extra about Angular concepts, components, and the overall structure of an Angular project.

If you don’t have already got a Firebase Database, you should use your Google account credentials to log in to Firebase and comply with the prompts. As soon as that is arrange, create a mission:

  1. From Firebase’s home page, choose Go to Console within the top-right nook of the location.
  2. Below “Your Firebase tasks”, choose Add Mission.
  3. Observe the prompts to create a brand new mission.
    Firebase website page asking the user to create a new project

  4. As soon as accomplished, the mission will open. On the left facet of the display, there’s a panel that lists the options Firebase gives. Hover over the icons till you see Firestore Database, and choose it.
    Page in Firebase with Create Database button

  5. Choose Create database, and comply with the prompts to create a database.
  6. When choosing the safety guidelines, choose Begin in take a look at mode. This may be modified later to make sure the info is safer. You’ll be able to learn extra about Firestore safety guidelines following the Firebase Documentation.
    Firebase prompt asking the user to choose the Database Security Rules

  7. As soon as accomplished, the database will open. The database construction makes use of Collections, which is actually the identical idea as database tables. For instance, for those who wanted two tables, one to retailer account info, and one to retailer consumer’s info, you’d create two collections named Account and Person.
  8. Choose Begin assortment and add a Assortment ID referred to as “Person”.
    Firebase prompt asking user to Create a new Collection

  9. Add the primary file, with details about one consumer. Click on on Add discipline so as to add three new fields: firstName (string), lastName (string), and vipMember (boolean). The Doc ID might be auto generated.
    Firebase Prompt to Add New Records to a Collection

  10. Click on Save.
  11. So as to add extra information to the “Person” assortment, click on on Add doc (add doc is the equal of including a brand new file or consumer). Add 4 extra customers with the identical three fields.

MAKEUSEOF VIDEO OF THE DAY

The database is now arrange with some take a look at knowledge.

Combine Firebase into Your Angular Software

To entry this knowledge in your native Angular software, first configure some app settings to hook up with the Firebase database:

  1. In Firebase, go to the left-hand panel and click on on Mission Overview.
  2. Choose the Internet button (indicated by Angle brackets).
  3. Register your native app by including the identify of the app.
    Firebase page asking the user to enter their App name to Register their App to Firebase

  4. Set up Firebase in your native Angular software.
    npm i firebase
  5. Firebase will then show some configuration particulars. Save these particulars and click on Proceed to Console.
  6. Primarily based on the small print offered within the earlier step, copy the next code into setting.prod.ts and setting.ts within the Angular software.
    export const setting = {
    manufacturing: true,
    firebaseConfig: {
    apiKey: "your-api-key",
    authDomain: "your-auth-domain",
    projectId: "your-project-id",
    storageBucket: "your-storage-buckey",
    messagingSenderId: "your-messaging-sender-id",
    appId: "your-api-id",
    measurementId: "your-measurement-id"
    }
    };
  7. AngularFirestore from @angular/hearth/firestore might be used to configure Firebase in Angular. Be aware that AngularFirestore shouldn’t be suitable with Angular Model 9 and above. Within the native Angular app, run:
    npm i @angular/hearth
  8. Add the Firestore and setting modules to the imports’ part in app.module.ts.
    import { AngularFireModule } from "@angular/hearth";
    import { AngularFirestoreModule } from "@angular/hearth/firestore";
    import { setting } from "../environments/setting";
  9. The Firestore modules additionally should be included within the imports array in app.module.ts.
    AngularFireModule.initializeApp(setting.firebaseConfig),
    AngularFirestoreModule,


Retrieve Knowledge from Firebase Utilizing a Service

It’s normally good observe to have one or a number of companies.ts information that you just use to particularly work together with the database. The features you add into the companies file can then be referred to as in different TypeScript information, pages, or different parts all through the appliance.

  1. Create a file referred to as service.ts within the src/app/companies folder.
  2. Add the AngularFirestore module to the imports part, and embrace it within the constructor.
    import { Injectable } from '@angular/core';
    import { AngularFirestore } from '@angular/hearth/firestore';
    @Injectable({
    providedIn: 'root'
    })
    export class Service {
    constructor(personal db: AngularFirestore) { }
    }
  3. Add a perform that returns a promise containing a listing of all customers. “this.db.assortment('Person')” is referring to the “Person” assortment within the database.
    getAllUsers() {
    return new Promise<any>((resolve)=> {
    this.db.assortment('Person').valueChanges({ idField: 'id' }).subscribe(customers => resolve(customers));
    })
    }
  4. To make use of this perform in one other TypeScript file, import the brand new service, and add it to the constructor.
    import { Service } from 'src/app/companies/service
    constructor(personal service: Service) {}
  5. Get the record of all customers utilizing the perform created within the companies file.
    async getUsers() {
    this.allUsers = await this.service.getAllUsers();
    console.log(this.allUsers);
    }


Add a New Report to the Firebase Database

Add a brand new file for a consumer into the Firebase Database.

  1. In companies.ts, add a brand new perform to create a brand new file. This perform takes in a brand new consumer’s ID, and all of their particulars. It makes use of Firestore’s set perform to ship that info to Firebase and create a brand new file.
    addNewUser(_newId:any, _fName:string, _lName:string, _vip:boolean) {
    this.db.assortment("Person").doc(_newId).set({firstName:_fName,lastName:_lName,vipMember:_vip});
    }
  2. Name the addNewUser() perform in one other TypeScript file. Do not forget to import the service and embrace it within the constructor, as proven earlier. Be at liberty to make use of a random ID generator to create the brand new ID for the consumer.
    this.service.addNewUser("62289836", "Jane", "Doe", true);


Replace Knowledge within the Firebase Database

Firebase has numerous features that make it among the best instruments obtainable. To replace sure fields in a selected file, use Firestore’s replace perform.

  1. Within the service.ts file, create a perform referred to as updateUserFirstName(). This perform will replace the primary identify of a selected consumer file. The perform takes within the ID of the file that must be up to date, and the brand new worth for the consumer’s first identify.
    updateUserFirstName(_id:any, _firstName:string) {
    this.db.doc(`Person/${_id}`).replace({firstName:_firstName});
    }
  2. To replace a number of fields for a similar file, simply develop on the fields being entered inside Firestore’s replace perform. As an alternative of simply firstName, add lastName to replace that with a brand new worth as effectively.
    updateUserFullName(_id:any, _firstName:string, _lastName:string) {
    this.db.doc(`Person/${_id}`).replace({firstName:_firstName,lastName:_lastName});
    }
  3. Any of the above features can be utilized in different TypeScript information.
    this.service.updateUserFirstName("vLBnSegFl1pD7XQ42TBv", "Kay");
    this.service.updateUserFullName("vLBnSegFl1pD7XQ42TBv", "Kay", "Jones");


Delete a Report From the Firebase Database

To delete a file, use the Firestore’s delete perform.

  1. Within the service.ts file, create a perform referred to as deleteUser(). This perform takes within the ID of the file that must be deleted.
    deleteUser(_id:any) {
    this.db.doc(`Person/${_id}`).delete();
    }
  2. The above perform can then be utilized in different TypeScript information.
    this.service.deleteUser("vLBnSegFl1pD7XQ42TBv");

Retrieve Firebase Knowledge Utilizing Queries and Filters

The “the place” filter can filter the outcomes which can be returned based mostly on a selected situation.

  1. In companies.ts, create a perform that will get all VIP customers (that is if the vipMember discipline is about to true). That is indicated by the “ref.the place(‘vipMember’, ‘==’, true)” a part of the Firebase name beneath.
    getAllVipMembers() {
    return new Promise<any>((resolve)=> {
    this.db.assortment('Person', ref => ref.the place('vipMember', '==', true)).valueChanges().subscribe(customers => resolve(customers))
    })
    }
  2. Use this perform in one other TypseScript file.
    async getAllVipMembers() {
    this.vipUsers = await this.service.getAllVipMembers();
    console.log(this.vipUsers);
    }
  3. The question might be modified so as to add different operations comparable to Order By, Begin At, or Restrict. Modify the getAllVipMembers() perform in companies.ts to order by the final identify. The Order By operation might require an index to be created in Firebase. If so, click on on the hyperlink offered within the error message within the console.
    getAllVipMembers() {
    return new Promise<any>((resolve)=> {
    this.db.assortment('Person', ref => ref.the place('vipMember', '==', true).orderBy('lastName')).valueChanges().subscribe(customers => resolve(customers))
    })
    }
  4. Modify the question to solely return the primary three information. The Begin At and Restrict operations can be utilized for this. That is helpful if it’s essential to implement paging, which is when a sure variety of information are proven per web page.
    getAllVipMembers() {
    return new Promise<any>((resolve)=> {
    this.db.assortment('Person', ref => ref.the place('vipMember', '==', true).orderBy('lastName').startAt(0).restrict(3)).valueChanges().subscribe(customers => resolve(customers))
    })
    }


Add Extra Knowledge to Firebase and Extra Requests within the Angular App

There are lots of different question mixtures you may discover when attempting to retrieve knowledge from a Firebase database. Hopefully you now perceive how one can arrange a easy Firebase database, how one can join it to an area Angular software, and how one can learn and write to the database.

You may also study extra in regards to the different companies that Firebase gives. Firebase is without doubt one of the many platforms you may combine with Angular, and no matter in case you are at a newbie or superior stage, there’s at all times a lot extra to study.


AngularJS on a typewriter

Prime 8 Angular Programs for Freshmen and Superior Customers

Learn Subsequent


About The Creator

Leave a Comment

Your email address will not be published. Required fields are marked *