Firebase is a platform that provides you with a multitude of services to assist with building and scaling an awarding. Some of these features include hosting services, information storage, and the power to rail data analytics.

This tutorial focuses mainly on how to create and add information to a Firebase database, and how to perform create, read, write, and delete operations to the database from a local Angular awarding.

How to Create and Add Data to a Firebase Database

Assuming y'all already have an Athwart application prepare and running locally, information technology will demand to exist connected to a Firebase database in order to shop and access data. If y'all are not familiar with Athwart, you can read more than virtually Athwart concepts, components, and the overall structure of an Angular project.

If you exercise not already accept a Firebase Database, yous tin employ your Google account credentials to log in to Firebase and follow the prompts. Once this is set up, create a project:

  1. From Firebase'southward dwelling house folio, select Go to Console in the top-right corner of the site.
  2. Under "Your Firebase projects", select Add Project.
  3. Follow the prompts to create a new projection.
    Firebase website page asking the user to create a new project
  4. Once completed, the project volition open. On the left side of the screen, in that location is a console that lists the features Firebase provides. Hover over the icons until you come across Firestore Database, and select it.
    Page in Firebase with Create Database button
  5. Select Create database, and follow the prompts to create a database.
  6. When selecting the security rules, select First in test style. This can be changed afterwards to ensure the information is more secure. You can read more about Firestore security rules following the Firebase Documentation.
    Firebase prompt asking the user to choose the Database Security Rules
  7. Once completed, the database will open. The database construction uses Collections, which is essentially the same concept as database tables. For instance, if you needed two tables, ane to store account information, and one to store user's information, yous would create two collections named Business relationship and User.
  8. Select Offset collection and add a Collection ID called "User".
    Firebase prompt asking user to Create a new Collection
  9. Add the outset record, with information about 1 user. Click on Add together field to add three new fields: firstName (cord), lastName (string), and vipMember (boolean). The Certificate ID tin can be motorcar generated.
    Firebase Prompt to Add New Records to a Collection
  10. Click Salvage.
  11. To add more than records to the "User" drove, click on Add certificate (add together document is the equivalent of calculation a new tape or user). Add four more users with the same three fields.

The database is now set up with some test information.

How to Integrate Firebase into Your Angular Application

To admission this data in your local Athwart application, outset configure some app settings to connect to the Firebase database:

  1. In Firebase, get to the left-mitt panel and click on Project Overview.
  2. Select the Web button (indicated by Angle brackets).
  3. Register your local app by adding the name of the app.
    Firebase page asking the user to enter their App name to Register their App to Firebase
  4. Install Firebase in your local Angular awarding.
                    npm i firebase
  5. Firebase will then display some configuration details. Save these details and click Continue to Panel.
  6. Based on the details provided in the previous step, copy the following code into environment.prod.ts and environment.ts in the Angular application.
                                      export                  const                  surround = {
    production: true,
    firebaseConfig: {
    apiKey: "your-api-fundamental",
    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 @athwart/fire/firestore will exist used to configure Firebase in Athwart. Notation that AngularFirestore is not compatible with Angular Version nine and above. In the local Angular app, run:
                    npm i                  @angular/fire
  8. Add the Firestore and environment modules to the imports' section in app.module.ts.
                                      import                  { AngularFireModule }                  from                  "@athwart/burn down";
    import { AngularFirestoreModule } from "@angular/fire/firestore";
    import { environment } from "../environments/surroundings";
  9. The Firestore modules also need to be included in the imports array in app.module.ts.
                                      AngularFireModule                  .initializeApp(environment                  .firebaseConfig),
    AngularFirestoreModule,

How to Remember Data from Firebase Using a Service

It is usually skillful practice to take ane or multiple services.ts files that you use to specifically interact with the database. The functions you add into the services file can then be chosen in other TypeScript files, pages, or other components throughout the application.

  1. Create a file called service.ts in the src/app/services binder.
  2. Add together the AngularFirestore module to the imports section, and include information technology in the constructor.
                                      import                  { Injectable }                  from                  '@angular/cadre';
    import { AngularFirestore } from '@angular/fire/firestore';
    @Injectable({
    providedIn: 'root'
    })
    consign class Service {
    constructor(private db: AngularFirestore) { }
    }
  3. Add a part that returns a promise containing a list of all users. "this.db.collection('User')" is referring to the "User" collection in the database.
                    getAllUsers() {
    return new Hope<any>((resolve)=> {
    this.db.drove('User').valueChanges({ idField: 'id' }).subscribe(users => resolve(users));
    })
    }
  4. To use this part in another TypeScript file, import the new service, and add information technology to the constructor.
                                      import                  { Service }                  from                  'src/app/services/service
    constructor(private service: Service) {}
  5. Go the list of all users using the function created in the services file.
                                      async                  getUsers() {
    this.allUsers = await this.service.getAllUsers();
    console.log(this.allUsers);
    }

How to Add a New Record to the Firebase Database

Add a new tape for a user into the Firebase Database.

  1. In services.ts, add a new part to create a new record. This function takes in a new user'southward ID, and all of their details. It uses Firestore's set function to ship that information to Firebase and create a new record.
                                      addNewUser(_newId                  :whatever, _fName                  :string, _lName                  :string, _vip                  :boolean)                  {
    this .db .collection(&quot;User&quot;).doc(_newId).set({firstName:_fName,lastName:_lName,vipMember:_vip});
    }
  2. Call the addNewUser() role in another TypeScript file. Don't forget to import the service and include it in the constructor, as shown earlier. Experience free to use a random ID generator to create the new ID for the user.
                    this.service.addNewUser("62289836",                  "Jane",                  "Doe", true);

How to Update Data in the Firebase Database

Firebase has lots of functions that make information technology one of the best tools available. To update certain fields in a detail record, use Firestore'south update function.

  1. In the service.ts file, create a function called updateUserFirstName(). This role volition update the first proper name of a chosen user record. The part takes in the ID of the record that needs to exist updated, and the new value for the user's beginning name.
                                      updateUserFirstName(_id                  :whatever, _firstName                  :string)                  {
    this.db.physician(`User/${_id}`).update({firstName:_firstName});
    }
  2. To update multiple fields for the same record, just aggrandize on the fields being entered inside Firestore'south update function. Instead of but firstName, add lastName to update that with a new value every bit well.
                                      updateUserFullName(_id                  :whatsoever, _firstName                  :cord, _lastName                  :cord)                  {
    this.db.doctor(`User/${_id}`).update({firstName:_firstName,lastName:_lastName});
    }
  3. Any of the above functions can be used in other TypeScript files.
                    this.service.updateUserFirstName("vLBnSegFl1pD7XQ42TBv",                  "Kay");
    this.service.updateUserFullName("vLBnSegFl1pD7XQ42TBv", "Kay", "Jones");

How to Delete a Record From the Firebase Database

To delete a record, employ the Firestore'due south delete function.

  1. In the service.ts file, create a function called deleteUser(). This role takes in the ID of the record that needs to be deleted.
                                      deleteUser(_id                  :any)                  {
    this.db.doc(`User/${_id}`).delete();
    }
  2. The to a higher place role tin can and so be used in other TypeScript files.
                    this.service.deleteUser("vLBnSegFl1pD7XQ42TBv");              

Retrieve Firebase Data Using Queries and Filters

The "where" filter can filter the results that are returned based on a specific status.

  1. In services.ts, create a part that gets all VIP users (this is if the vipMember field is set to true). This is indicated past the "ref.where('vipMember', '==', truthful)" role of the Firebase call below.
                    getAllVipMembers() {
    return new Promise<any>((resolve)=> {
    this.db.collection('User', ref => ref.where('vipMember', '==', true)).valueChanges().subscribe(users => resolve(users))
    })
    }
  2. Employ this function in another TypseScript file.
                                      async                  getAllVipMembers() {
    this.vipUsers = look this.service.getAllVipMembers();
    console.log(this.vipUsers);
    }
  3. The query tin be modified to add other operations such as Order By, Start At, or Limit. Modify the getAllVipMembers() function in services.ts to gild by the last proper name. The Order By functioning may require an index to exist created in Firebase. If this is the case, click on the link provided in the mistake bulletin in the console.
                    getAllVipMembers() {
    return new Promise<any>((resolve)=> {
    this.db.collection('User', ref => ref.where('vipMember', '==', true).orderBy('lastName')).valueChanges().subscribe(users => resolve(users))
    })
    }
  4. Modify the query to but render the first three records. The Start At and Limit operations can be used for this. This is useful if y'all need to implement paging, which is when a certain number of records are shown per folio.
                    getAllVipMembers() {
    return new Promise<whatsoever>((resolve)=> {
    this.db.collection('User', ref => ref.where('vipMember', '==', truthful).orderBy('lastName').startAt(0).limit(iii)).valueChanges().subscribe(users => resolve(users))
    })
    }

Add More Information to Firebase and More Requests in the Angular App

At that place are many other query combinations y'all tin explore when trying to retrieve information from a Firebase database. Hopefully you at present sympathise how to gear up a elementary Firebase database, how to connect it to a local Angular awarding, and how to read and write to the database.

You can also larn more virtually the other services that Firebase provides. Firebase is one of the many platforms you can integrate with Angular, and regardless of if you lot are at a beginner or avant-garde level, there is always so much more to larn.

Top 8 Angular Courses for Beginners and Advanced Users

Read Adjacent