Creating a Firebase database

Author: Damian Gemza

-

Creating the databases - Firebase

Creating a Firebase application:

As the first step, please execute the command below to install the two new dependencies: @angular/fire and firebase npm packages.


        npm install @angular/fire firebase --save
      

In order to take advantage of the benefits provided by Firebase, a database in real time and hosting, we need to create an application there.

To do this, open the following address in your web browser: https://console.firebase.google.com/.

After logging in to the Firebase service, you need to create a new application, which will be our PWA application. To do this, click the "Add Project" button and go through the short form in which you will provide the name of your project and some other required information.

After creating a new Firebase application, we have to add it to our Angular application. To do this, click Add Firebase to your web application — icon, and then copy the entire config object to the clipboard.

Then open the environment.prod.ts and environment.ts files in the src/environments directory, and copy into them the contents of the firebase object from the previous step.

Your environment file should look like below:


        export const environment = {
          production: true,
          firebase: {
            apiKey: 'AIzaSyDJhRi36BrDN7X0xREizJghcIpvXWTVEnQ',
            authDomain: 'xxxx-213c1.firebaseapp.com',
            databaseURL: 'https://xxxx-213c1.firebaseio.com',
            projectId: 'xxxx-213c1',
            storageBucket: 'xxxx-213c1.appspot.com',
            messagingSenderId: '948885513845'
          }
        };
      

After configuring the Firebase environment, you should start using it. To do this, open the file app.module.ts, and import two new modules in it: AngularFireModule and AngularFirestoreModule.

Your app.module.ts file should look like this below:


        import { BrowserModule } from '@angular/platform-browser';
        import { NgModule } from '@angular/core';

        import { AppComponent } from './app.component';
        import { ServiceWorkerModule } from '@angular/service-worker';
        import { environment } from '../environments/environment';
        import { MDBBootstrapModule } from 'angular-bootstrap-md';
        import {AngularFireModule} from '@angular/fire';
        import {AngularFirestoreModule} from '@angular/fire/firestore';

        @NgModule({
          declarations: [
            AppComponent
          ],
          imports: [
            BrowserModule,
            ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }),
            MDBBootstrapModule.forRoot(),
            AngularFireModule.initializeApp(environment.firebase),
            AngularFirestoreModule
          ],
          providers: [],
          bootstrap: [AppComponent]
        })
        export class AppModule { }

      

Creating a Firebase database:

Open your Firebase project, and from the left menu select the Develop -> Database tab (1), and then click the Create Database button and choose test mode.

After creating the database add new collection by clicking the "Add collection" button (2), and choose a name for your collection.

Modified files list

After setting up the new collection name, we have to define a few data fields in the new document. Let's call it: id: string, time: string, subject: string, location: string, description: string. At this point feel free to fill those fields with some dummy data.

Your collection in Firebase should look like this:

Modified files list

Generating the Firebase Service:

The last step in this lesson will be to create a service for communication with Firebase. To do this, open the terminal of your application, and then run the following command in it:


        ng generate service services/Firebase
      

Now we should fill our generated service with some logic. Paste the code below into FirebaseService class.


        import {Injectable} from '@angular/core';
        import {AngularFirestore, AngularFirestoreCollection} from '@angular/fire/firestore';
        import {Schedule} from '../app.component';

        @Injectable({
          providedIn: 'root'
        })
        export class FirebaseService {
          items: AngularFirestoreCollection<Schedule>;

            constructor(private db: AngularFirestore) {
              this.items = db.collection<Schedule>('Items');
              }

              addItem(item: any) {
                this.items.add(item);
              }

              getData() {
                return this.items;
              }
            }

      

Let me explain how this service works:

  • In the constructor we create a field called db of type AngularFirestore, and then in the items field we connect with Firebase and get the Items collection.
  • The addItem() method adds a new schedule to the Items collection in Firebase.
  • The getData() method returns the items field — thanks to this method we will retrieve data from Firebase.

Finally, open the main application module — AppModule — and then add the generated FirebaseService to the provider's array so that we can use it throughout the application.

At the end of the lesson your app.module.ts file should look like this:


        import {BrowserModule} from '@angular/platform-browser';
        import {NgModule} from '@angular/core';
        import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

        import {AppComponent} from './app.component';
        import {ScheduleItemComponent} from './schedule-item/schedule-item.component';

        import {MDBBootstrapModule} from 'angular-bootstrap-md';
        import {FormsModule, ReactiveFormsModule} from '@angular/forms';
        import { ServiceWorkerModule } from '@angular/service-worker';
        import { environment } from '../environments/environment';
        import {AngularFireModule} from '@angular/fire';
        import {AngularFirestoreModule} from '@angular/fire/firestore';
        import {FirebaseService} from './services/firebase.service';

        @NgModule({
          declarations: [
            AppComponent,
            ScheduleItemComponent
          ],
          imports: [
            BrowserModule,
            BrowserAnimationsModule,
            MDBBootstrapModule.forRoot(),
            FormsModule,
            ReactiveFormsModule,
            ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }),
            AngularFireModule.initializeApp(environment.firebase),
            AngularFirestoreModule
          ],
          providers: [FirebaseService],
          bootstrap: [AppComponent]
        })
        export class AppModule {
        }

      

If something doesn't work for you, then please check the code for this lesson on our repository


Rate this lesson

Previous lesson Download Next lesson

Spread the word:
Do you need help? Use our support forum

About the author

User avatar
Damian Gemza
Damian is a front-end developer. He is passionate about everything related to the world of Web Development. He is interested in Angular and everything that is connected with it. He knows and uses the Ionic framework and Progressive Web Apps technology. Recently he has started to write tutorials related to Web Development.

Install MDB CLI
It's the fastest way to create and host MDB projects
Free Download

Sign up to follow your progress and get additional benefits