How to build an authentication in Angular using Firestore

How to build an authentication in Angular using Firestore

In this tutorial, we are going to build an authentication system in Angular using Google’s Cloud Firestore.

Most of the application we build require some kind of Authentication and the simplest and fastest way to get started with that is by using the Firestore. Firestore is a flexible, scalable database for mobile, web and server development.

WHAT YOU WILL LEARN

In this article, you will learn to develop a fully functioning authentication system in Angular using Firestore. We will be using the official tool for Angular and Firebase integration – AngularFire. AngularFire allows you to work with Cloud Firestore, the new flagship database for mobile app development. It improves on the successes of Real-time Database with a new, more intuitive data model. Cloud Firestore also features richer, faster queries and scales better than Realtime Database.

PREREQUISITES

In order to follow along with this tutorial please ensure you have downloaded and installed the Angular IDE. Ensure that the latest version of Angular CLI is installed on your computer. You also need a Google account to be able to sign in to Firebase Console, where you will be creating the app which we will work with, in this tutorial.

CREATE AN ANGULAR PROJECT AND A FIREBASE APP

We’ll be using the latest version of all the tech libraries and stacks as at the time of this writing. Navigate to File -> New -> Angular Project. Then choose to Create a New Project with the following, versions of software as is in the screenshot below.

Create a New Angular Project from Angular IDE

After setting up the project to use the versions and giving it a Project name of AngularAuth click finish to create and install, this will ideally take some time, depending on how fast your internet is, so be patient.

Create a New Angular Project from Angular IDE

Once the project is created, the next thing to do is create an app in Firebase, so navigate to the Firebase Console and then click on Add Project to create a new project. Give it a name, I’ll call mine AngularAuth, then click on Create Project afterward.

Now after the project has been created, you will be redirected to the project’s overview page, there you are meant to choose the option – **_Add Firebase to your web app. _**On clicking that, you will get a pop up with all the info such as API key that you need to be able to interact with your newly created Firebase app from the Angular application that we created in Angular IDE. That’s it for now with Firebase, let’s go back to the Angular IDE to create some components.

We need a Homepage, Login page, and Sign Up page to showcase how our Authentication is working. So we need to create an Angular component for each of these pages. We will use one of the features that make Angular IDE so awesome, the Create Component shortcut, Navigate to File -> New -> **Component**to create a new component.

Give the first component a name – homepage as in the screenshot below and uncheck the Create Component with Unit Test flag, because Unit Testing is beyond the scope of this tutorial,but we can leave the Generate Component using the prefix location flag, which is the default from Angular. The prefix is simply the word that goes before the selector of every component you generate with the CLI. If you want to know more about it or change the prefix, read more about it on this StackOverflow question here.

Click Finish when you are done. This will automatically run the command **_ng g component homepage –spec false _**in Angular IDE’s terminal.

Now let us run our app to confirm everything is working. Go into the Angular IDE and type the command ng serve

On running ng serve I got the following error

~/Workspaces/Dunebook/AngularAuth
$ ng serve
You seem to not be depending on "@angular/core". This is an error.

If you got that same error, run npm install to install the npm packages required to get your app up and running. Check out this page to install yarn, if you don’t have it yet. After running npm install successfully, the ng serve command will now run successfully. Visit this link to see your app working.

Now, let’s go ahead and remove the default content that came with the new application. Navigate to src/app/app.component.html to see the code. Select all content of this file and delete it. When you hit save and check your browser now, the page should be blank. The app.component.html file now becomes the new base/host for our homepage. Go ahead and add the selector of the homepage component there. To do that, type the following code (for some unknown reason I could not paste the code so I’ll attach the screenshot). Save it now and your site should reload to show the content of homepage.component.html.

The app-homepage is the selector for the homepage component we created earlier.

Next, we will create the other two components needed to run the app and then install AngularFire2 and Firebase. Run the following commands to do that.

ng g c login --spec false && ng g c signup --spec false && npm install firebase angularfire2

The above command will create a LoginComponent, SignupComponent and then install firebase and angularfire2 npm packages.

Now, with the installed npm packages we need configure our Firebase application to enable it to be able to communicate with your Angular application.

Firebase Config set up for Angular Authentication

First, we will import the AngularFire modules to the app.module.ts file. My app.module.ts file looks like this after the new config is added. The lines in bold need to be added to your app.module.ts

When you click on **Add Firebase to your web app **you should get a pop up similar to the image below.

Firebase Auth Config for Authentication in Angular

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
 import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AppComponent } from './app.component';
import { HomepageComponent } from './homepage/homepage.component';
import { LoginComponent } from './login/login.component';
import { SignupComponent } from './signup/signup.component';
 // Copy the firebaseConfig from your created project on the firebase console. Here, click on the project name and then on the project dashboard, click on Add firebase to your web app. Replace the values below with yours, values below will not work for you because I have removed some characters from it.
const firebaseConfig = {
apiKey: 'AIzaSyAywNGLBVmlk98jwaeqsFdm1hNMQ',
authDomain: 'angularauth-502.firebaseapp.com',
databaseURL: 'https://angularauth-502.firebaseio.com',
projectId: 'angularauth-502',
storageBucket: 'angularauth-502.appspot.com',
messagingSenderId: '11240551'
};
 @NgModule({
declarations: [
AppComponent,
HomepageComponent,
LoginComponent,
SignupComponent
],
imports: [
BrowserModule,
FormsModule,
AngularFireModule.initializeApp(firebaseConfig),
AngularFireAuthModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Next, we will set up the Authentication methods, by clicking on the Authentication link described in the screenshot above. Once there, enable Sign-in for Email/Password and Google and then save. To enable for other providers you need an API key and API secret. Which can be easily generated by visiting the developers’ section of each of the providers.

Click on the Database on the sidebar at Firebase and then click on TRY FIRESTORE BETA. Then click ENABLE.

Enabling Firestore Firebase Database

Upon creation of the Database, check the Rules tab and make sure the content is similar to this:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}

As at the time of this writing. There was a bug in the Firebase npm package, the following errors were displayed in the console. And according to this thread on Github, we need to downgrade Firebase to version 4.8.0 and upgrade AngularFire to version 5.0.0-rc.5. Remove the ^ at the beginning of the versions so as to download the exact version that we want. After changing it run yarn install to change the version.

"angularfire2": "5.0.0-rc.5-next",
"firebase": "4.8.0",

Take note that if you are using a version of Firebase and AngularFire that is higher, you might not need to make these changes. The versions causing the errors are Firebase version 4.8.1 and AngularFire 5.0.0-rc.4.

With these changes effected correctly, the errors should be gone. Now let’s go ahead and use AngularFire and Firebase in our project. First, we need to create a service file which will serve all the methods that we need to login and logout. Go to the Angular IDE and follow the direction as described in the screenshot below.

Creating a New Service in Angular IDE

Creating a New Service and giving it a name in Angular IDE

Now, let’s go to the auth.service.ts file and add some code to it.

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/switchMap';

@Injectable()
export class AuthService {

  constructor(
    private afAuth: AngularFireAuth,
    private router: Router) {}

  login(email: string, password: string) {
    this.afAuth.auth.signInWithEmailAndPassword(email, password)
    .then(value => {
      console.log('Nice, it worked!');
      this.router.navigateByUrl('/profile');
    })
    .catch(err => {
      console.log('Something went wrong: ', err.message);
    });
  }

  emailSignup(email: string, password: string) {
    this.afAuth.auth.createUserWithEmailAndPassword(email, password)
    .then(value => {
     console.log('Sucess', value);
     this.router.navigateByUrl('/profile');
    })
    .catch(error => {
      console.log('Something went wrong: ', error);
    });
  }

  googleLogin() {
    const provider = new firebase.auth.GoogleAuthProvider();
    return this.oAuthLogin(provider)
      .then(value => {
     console.log('Sucess', value),
     this.router.navigateByUrl('/profile');
   })
    .catch(error => {
      console.log('Something went wrong: ', error);
    });
  }

  logout() {
    this.afAuth.auth.signOut().then(() => {
      this.router.navigate(['/']);
    });
  }

  private oAuthLogin(provider) {
    return this.afAuth.auth.signInWithPopup(provider);
  }
}

The first thing we need to do after creating a Service method is to add it to the providers array in the app.module.ts file, then after that we need to create routes for the components we created earlier and also create two more components, the EmailComponent and ProfileComponent. Use the same method we used to create components earlier to create those components. Your app.module.ts file should now look like this (The most significant changes are highlighted in bold):

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

import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';

import { AppComponent } from './app.component';
import { AuthService } from './auth.service';
import { HomepageComponent } from './homepage/homepage.component';
import { LoginComponent } from './login/login.component';
import { SignupComponent } from './signup/signup.component';
import { ProfileComponent } from './profile/profile.component';

import { AppRoutingModule } from './app-routing.module';
import { EmailComponent } from './email/email.component';

const firebaseConfig = {
  apiKey: 'AIzaSyAywNGLBVmlk98dkqahOj1hNMQ',
  authDomain: 'angularauth-502.firebaseapp.com',
  databaseURL: 'https://angularauth-502.firebaseio.com',
  projectId: 'angularauth-502',
  storageBucket: 'angularauth-502.appspot.com',
  messagingSenderId: '1124055'
};

@NgModule({
  declarations: [
    AppComponent,
    HomepageComponent,
    LoginComponent,
    SignupComponent,
    ProfileComponent,
    EmailComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(firebaseConfig),
    AngularFireAuthModule
  ],
  providers: [ AuthService ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Next, we’ll create the AppRoutingModule where we will create our routes. Create a file app-routing.module.ts in the src/app folder, then fill it up with the following content.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { ProfileComponent } from './profile/profile.component';
import { SignupComponent } from './signup/signup.component';
import { EmailComponent } from './email/email.component';

const routes: Routes = [
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'email-login', component: EmailComponent },
  { path: 'signup', component: SignupComponent },
  { path: 'profile', component: ProfileComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

Now let’s go ahead and work in our LoginComponent file navigate to the login/login.component.ts, the method we will use there is the googleLogin().

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private authService: AuthService) { }

  ngOnInit() {}

  loginGoogle() {
    this.authService.googleLogin();
  }
}

And fill up the component file, login.component.html like so:

Angular Authentication with Firestore Login Form

Before we go ahead and verify that everything is working, we need to change the content of the app.component.html file:

Replace

<app-homepage></app-homepage> with <code><router-outlet></router-outlet>

We should also add some styling to the form by editing the src/styles.css file, add the following css code to it:

body {
    background: #E2E4E6;
    padding-top: 4em;
}

.form-container {
    background: white;
    padding: 3.5em;
    width: 500px;
    position: fixed;
    left: 45%;
    margin-left: -250px;
}

button {
    padding: 0.5em;
    width: 100%;
    cursor: pointer;
    margin-bottom: 15px;
    font-size: 1.3em;
}

.google {
    border: 1px solid #95989A;
    background: #fff;
    background-size: 25px;
}

.email {
    background: #ECECEC;
    background-size: 25px;
}

.create-account-txt {
    text-align: center;
    display: block;
    margin: 15px 0;
}

.auth-btn {
    background: #3B8598;
    color: white;
}

input.input-txt {
    background: #fff !important;
    padding: 0.5em 1em;
    font-size: 1.3em;
    border: 1px solid #BBBBBB;
    width: 90%;
    margin-bottom: 1em;
}

Now the login page looks like this:

Angular Firebase Authentication Email Login Form

Log in with Google Account now works, next, we will implement Logging in with Email and then after that, work on the Signup form. Navigate to the email/email.component.ts file:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-email',
  templateUrl: './email.component.html',
  styleUrls: ['./email.component.css']
})
export class EmailComponent implements OnInit {

  constructor(
    private authService: AuthService) { }

  ngOnInit() {}

  onSubmit(formData) {
    if (formData.valid) {
      console.log(formData.value);
      this.authService.login(
        formData.value.email,
        formData.value.password
      );
    }
  }
}

Next, let’s navigate to the email/email.component.html file and add the following (I’m adding the screenshot of the template because it’s been interpreted incorrectly):

Angular Authentication with Firestore Email Login Form

The login form now looks like this:

Angular Firebase Authentication Email Login Form

Next, let’s work on the Signup form and its component:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {

  constructor(public authService: AuthService) { }

  ngOnInit() {}

  onSubmit(formData) {
    if (formData.valid) {
      console.log(formData.value);
      this.authService.emailSignup(
        formData.value.email,
        formData.value.password
      );
    }
  }
}

And then the template:

Angular Firebase Authentication Email Sign up Form

Lastly, the profile component which is the simplest of all, there we just need to add a Sign Out button that will take the user back to the Login Page.

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {

  constructor(public authService: AuthService) { }

  ngOnInit() {}

  signOut() {
    this.authService.logout();
  }
}

Angular Firebase Authentication Profile Page

Conclusion

There’s still room for improvement, we can check the state of the current user and guard the profile page so that a stranger can’t go to User’s profile without Logging in. If you are reading this, you’ve probably navigated your way through this tutorial successfully.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Learn More

Angular 7 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

The Web Developer Bootcamp

Spring & Hibernate for Beginners (includes Spring Boot)

Spring Framework Master Class - Learn Spring the Modern Way!

Master Microservices with Spring Boot and Spring Cloud

Front-end Developer Handbook 2019

Angular 7 + Spring Boot CRUD Example

MEAN Stack Tutorial – Angular 7 CRUD App with Bootstrap 4

Node, Express, Angular 7, GraphQL and MongoDB CRUD Web App

Angular 8 + Spring Boot 2.2: Build a CRUD App Today!

React vs. Vue vs. Angular

Angular + Typescript = Powerful Web Apps

Build a CRUD App with Angular and Firebase

Firebase as simple database to React app

Originally published on https://www.dunebook.com/

How to deploy Angular App to Firebase using Angular CLI 8.3+

How to deploy Angular App to Firebase using Angular CLI 8.3+

In this tutorial, we’ll create the production bundles of our Angular application and deploy it to Firebase using Angular CLI 8.3+.

You have finally developed your Angular application and you are ready to deploy it to a hosting provider and show it to the world! But, you think, you still have to do so much work to host the application. Fortunately for you, that's not true any more thanks to the latest 8.3+ version of Angular CLI which added a new command to the Angular developer arsenal, just like the ng add command introduced in Angular 7.

The command is ng deploy and as you can guess, it allows you to deploy your Angular application from the command-line using Angular CLI. The command doesn't work out of the box as you need to use it with the ng add command to install a |CLI builder](https://angular.io/guide/cli-builder) that gives your project the required deployment capability to work with a specific hosting provider. This is quite expected since there are various providers, each one with its own configuration.

In this tutorial, we’ll create the production bundles of our Angular application and deploy it to Firebase using Angular CLI 8.3+.

We assume that you already have initialized a project with Angular CLI and that you have installed or updated your project to the latest version of Angular CLI.

How to automatically deploy your Angular project to Firebase? This can be done in 5 easy steps:

  • Step 0 - Setting up your Firebase account and creating a project
  • Step 1 - Adding the Firebase deployment capability to your Angular project
  • Step 2 - Providing the authorization code to Firebase CLI
  • Step 3 - Selecting a Firebase project
  • Step 4 - Building & deploying your Angular project to Firebase
Step 0 - Setting up your Firebase account and creating a project

In the first step, you need to set up a Firebase account and create a project.

Go to the Getting started page and simply follow the instructions there to set up a Firebase account.

Once you have created a Firebase account, you need to create a project in Firebase's dashboard. Simply click on Add project to create a new project.

A box will show up asking you to provide some information about your project. Provide a name for your project and click on the CREATE PROJECT button.

That's it! You have successfully created a Firebase account and project. Let's now head back to the Angular project.

Step 1 - Adding the Firebase deployment capability to your Angular project

The first step is to navigate to your Angular project and add the deployment capability for your target hosting provider. In our case, it's Firebase.

Go to your terminal, and run the following command from the root of your project:

$ ng add @angular/fire

This will add the Firebase deployment capability to your project.

Step 2 - Providing the authorization code to Firebase CLI

The CLI will ask you to Paste authorization code here:**** and will open your default web browser and ask you to give Firebase CLI permissions to administer your Firebase account:

After you log in with the Google account, you’ll be provided with the authorization code:

Step 3 - Selecting a Firebase project

Next, you’ll be asked: Please select a project: (Use arrow keys or type to search). You should have created a Firebase project before.

The CLI will create the firebase.json and .firebaserc files and update the angular.json file accordingly.

Step 4 - Building & deploying your Angular project to Firebase

Finally, you can deploy your application to Firebase, using the following command:

$ ng deploy

The command will build your application (similarly to the ng deploy --prod command), and send the production assets to Firebase.

Conclusion

Thanks to Angular CLI 8.3+, it's now easier than ever to deploy your Angular project to popular hosting and cloud platforms such as Firebase, GitHub, Now and Netlify. You can also search npm for the required package to target your platform, if one doesn't exist or if you're deploying to a self-managed server, you can either create a builder that allows you to use the ng deploy command or manually deploy your app. Check out the official docs for more information.

How to Use Algolia with Firebase Angular Apps

How to Use Algolia with Firebase Angular Apps

Algolia is a super powerful, scalable API service that allows developers to send different forms of data into their platform and quickly perform search, sort and complex filter queries on top of it.

What is Algolia?

Algolia is a super powerful, scalable API service that allows developers to send different forms of data into their platform and quickly perform search, sort and complex filter queries on top of it. The service is incredibly fast, by using replica indexes to pre-build common query conditions to send your data back as quick as possible.

Why use Algolia with Firebase?

Firebase has come a long way in terms of its accessibility with querying data structures, especially in Firestore. Even with these advancements, it has limitations and often time requires pre-sorted data, using Firebase’s syntax sugar with push ids (push ids contain a date hash in their generation) and sacrificing extra reads/writes and straight forward object structure. Firebase also officially recommends Algolia for performing full-text search operations in Firestore.

Getting Started

In this working example, we will be using Firebase Cloud Functions with triggers to help assist with syncing data changes from Firestore over to Algolia. We will also be using the Algolia Node.JS and JavaScript client module for interacting with their service.

Firebase Cloud Functions

In your functions directory you will need to install the following dependencies to leverage Algolia.

npm install --save algoliasearch @types/algoliasearch

For this example we will listen for whenever a new user document is created, updated or deleted in our custom Firestore collection “users”.

For each of the below examples you will need to replace appId and apiKey with your own access tokens generated through Algolia’s admin panel.

user.onCreate.ts

The userOnCreate trigger is dispatched every time a new document is created in the users collection. In the example below we initialize Algolia with our app’s id and unique API key and initialize the index we want to use in Algolia. Algolia recommends naming your index by the instance/environment you are working with (i.e. dev_, prod_, staging_, next_).

We are also replicating to indexes so that we can sort by the user’s name in either ascending or descending order. Algolia reserves objectID for correlating records in their world; we will use the new document’s path id.

import * as algoliasearch from 'algoliasearch';
import * as functions from 'firebase-functions';

export const userOnCreate = functions.firestore
.document('users/{id}')
.onCreate(async (change, context) => {
const user = change.data();
const client = algoliasearch('appId', 'apiKey');
const index = client.initIndex('dev_users');
await index.setSettings({
replicas: [
'dev_users_name_desc',
'dev_users_name_asc'
]
});
return index.addObject({
objectID: change.id,
...user
});
});

user.onUpdate.ts

The userOnUpdate trigger is very similar to the create trigger. The difference is that we do not need to re-specify the replica indexes since once we register them; they will automatically push data over to the replica indexes any time we write to the parent index (dev_users).

To reduce the operation cost, Algolia allows partial updates to only change specific properties on an index’s object.

import * as algoliasearch from 'algoliasearch';
import * as functions from 'firebase-functions';

export const userOnUpdate = functions.firestore
.document('users/{id}')
.onCreate(async (change, context) => {
const user = change.data();
const client = algoliasearch('appId', 'apiKey');
const index = client.initIndex('dev_users');
return index.partialUpdateObject({
objectID: change.id,
...user
});
});

user.onDelete.ts

The userOnDelete trigger is the simplest operation with an initialize and delete object call to remove the Algolia object by the objectID we defined earlier.

import * as algoliasearch from 'algoliasearch';
import * as functions from 'firebase-functions';

export const userOnDelete = functions.firestore
.document('users/{id}')
.onCreate(async (change, context) => {
const client = algoliasearch('appId', 'apiKey');
const index = client.initIndex('dev_users');
return index.deleteObject(change.id);
});

Export all of these constants to your root index.ts file. This will register them as new Firebase Cloud Functions when you build and deploy. At this point any time you change documents in Firestore (either directly through the Firebase Console or with your app) it will trigger these functions to push and sync data across to Algolia.

firebase deploy --only functions:userOnCreate,functions:userOnUpdate,functions:userOnDelete
Application Side
You can store Algolia’s search-only access token (this is different than the apiKey used in Cloud Functions) in your environments file to easily access/import it.

Create a simple service to easily interact with your Algolia indexes.

user.service.ts

import * as algoliasearch from 'algoliasearch';

@Injectable()
export class UserService {

client: algoliasearch.Client;

init(config: {
appId: string,
apiKey: string
}) {
this.client = algoliasearch('appId', 'apiKey');
}

fetchUsers(options: algoliasearch.QueryParameters) {
const userSearch = this.client.initIndex('dev_users');
return userSearch.search(options);
}

fetchUsersByNameAsc(options: algoliasearch.QueryParameters) {
const userSearch = this.client.initIndex('dev_users_name_asc');
return userSearch.search(options);
}

fetchUsersByNameDesc(options: algoliasearch.QueryParameters) {
const userSearch = this.client.initIndex('dev_users_name_desc');
return userSearch.search(options);
}

}

In your component, provide UserService and make the following method calls to test the response back from Algolia.

async ngOnInit() {
this.init({ appId: 'foo', apiKey: 'bar' });
const res = await this.fetchUsers({
page: 0,
length: 10,
query: 'Sean'
});
console.log('res', res);
}

This method call will attempt to load the first page of results, up to 10 records that has a searchable attribute that matches “Sean”.

Final Thoughts

Without getting too far into the weeds of Algolia’s client and explicitly focusing on syncing data over and quickly logging that information out; we can see that Algolia serves as a powerful interface to receive the exact data we need.

In our implementation on Hive, we use Algolia to handle paginated admin tables, infinite scroll experiences, pre-filtering collection records by specific conditions and sorting table data. You can also leverage Algolia as a read-only database, only storing/syncing documents that the client should have access to. This is powerful when using concepts such as soft deletes, where you stamp a document with a deletedAt timestamp in Firestore and remove the object from Algolia. By doing this, you can always recover the document back, but all querying logic from Algolia will treat the document as being deleted.

Thanks for reading. If you liked this post, share it with all of your programming buddies!

Further reading

☞ Learn and Understand AngularJS

☞ The Complete Angular Course: Beginner to Advanced

☞ Angular Crash Course for Busy Developers


Originally published on medium.com

Build a CRUD App with Angular 8 and Firebase

Build a CRUD App with Angular 8 and Firebase

This Angular 8/9 tutorial explains how to use Angular 8/9 with Firebase and Firestore to create an app that implements the common CRUD operations. How to add Firebase CRUD operations to your Angular 8 project that allow you to create, read, update and delete data from a Firestore database. How to set up Firebase in our Angular 8 project, and create a service for implementing Firebase CRUD operations using the Firestore realtime database.

In this tutorial, you'll be using Angular 8/9 with Firebase and Firestore to create an app that implements the common CRUD operations.

We'll see setp by step how to set up Firebase in our Angular 8 project, and create a service for implementing Firebase CRUD operations using the Firestore realtime database.

These are the steps of our Angular Firebase CRUD tutorial:

  • Step 1 - Creating your Angular 8 Project
  • Step 2 - Creating a Firebase Project and a Firestore Database
  • Step 3 - Installing and Adding Firebase to your Angular 8 Project.
  • Step 4 - Create an Angular 8 Model
  • Step 5 - Creating an Angular 8 Service
  • Step 6 - Creating a Component for Making CRUD Operations
What is CRUD?

CRUD stands for Create, Read, Update and Delete and refer to the operations that we run against a database to createn retrieve and update data. In this example, the database is a Firestore database that exists on the cloud.

Note: This tutorial works with Angular 9.

Prerequisites

Before starting this tutorial, you first need to make sure, you have:

  • A recent version of Node.js (v10+) and NPM installed on your system,
  • The latest Angular CLI 8 installed on your system.

If you have the prerequisites, you are ready to start creating your project!

Step 1 - Creating your Angular 8 Project

The first step in this tutorial is creating a new Angular 8 project using the CLI.

Head over to your terminal and run the following command:

$ ng new angular-firebase-crud

The CLI will ask if you want to add routing to your project (you can choose any option you want) and which style sheet format you want to use (You can select CSS).

After that, your project files will be generated and your project's dependencies will be installed.

Step 2 - Creating a Firebase Project and a Firestore Database

Now that your project is generated, you need to proceed with creating a Firebase project and a Firestore database. For this matter, you simply need to go to the Firebase Console and create a new Firebase project.

Next head to the Project Overview >Develop >Database page and create a new Firestore database. For now, make sure you enable test mode so you don't need any permissions to access the database.

Step 3 - Installing and Adding Firebase to your Angular 8 Project.

After creating your Firebase project and your Firestore database you next need to install the firebase and @angular/fire packages as follows:

$ cd ./angular-firebase-crud
$ npm install --save firebase @angular/fire

Next go to your Firebase project overview then click on web and copy the config data.

Next, open the environments/environment.ts file in your Angular 8 project and add the firebaseConfig object inside the environment object.

export const environment = {
  production: false,
  firebaseConfig : {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    databaseURL: "YOUR_DATABASE_URL",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID"
  }
};

Finally, you have to set up Firebase in your project. Open the src/app/app.module.ts file and update it accordingly:

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

@NgModule({
        // [...]
    imports: [
        // [...]
        AngularFireModule.initializeApp(environment.firebaseConfig),
        AngularFireDatabaseModule
    ],

You simply import AngularFireModule and AngularFireDatabaseModule and you add them to the imports array of the main application module.

You also call the initializeApp() method of AngularFireModule to pass the configuration object that you added earlier to the environments/environment.ts file.

That's it, you now have added Firebase and Firestore to your Angular 8 project.

Step 4 - Create an Angular 8 Model

After setting up Firestore in your project, you can proceed with creating a model class. In the simple example, we suppose that you are creating an insurance app where we need to manage a set of policies.

An insurance application will often contain more that one type of data like clients, employees and policies etc. In this example, we'll just focus on the policy entity.

Let's create a model for our insurance policy entity as follows:

$ ng g class policy --type=model

Next, open the src/policy.model.ts file and update it as follows:

export class Policy {
    id: string;
    policyNumber: string;
    creationDate: Date;
    effectiveDate: Date;
    expireDate: Date;
    paymentOption: string;
    policyAmount: number;
    extraInfo: string;
}

This is an example of an insurance policy with many fields and relationships with other entities omitted for the sake of simplicity.

Step 5 - Creating an Angular 8 Service

An Angular service allows you to encapsulate the code that could be repeated in many places in your project. Using the Angular CLI, run the following command to generate a service:

$ ng g service policy

Next, open the src/policy.service.ts file and update it accordingly.

First, import AngularFirestore and the Policy model as follows:

import { AngularFirestore } from '@angular/fire/firestore';
import { Policy } from 'src/app/policy.model';

Next, inject AngularFirestore in your service via its constructor:

export class PolicyService {
  constructor(private firestore: AngularFirestore) { }
}

Next, add the getPolicies() method to retrieve the available policies from the Firestore collection:

getPolicies() {
    return this.firestore.collection('policies').snapshotChanges();
}

You also need to add the createPolicy() method to persist an insurance policy in the Firestore database:

createPolicy(policy: Policy){
    return this.firestore.collection('policies').add(policy);
}

Next, you need to add the updatePolicy() method to update an insurance policy by its identifier:

updatePolicy(policy: Policy){
    delete policy.id;
    this.firestore.doc('policies/' + policy.id).update(policy);
}

Finally, you can add the deletePolicy() method to delete an insurance policy by its identifier:

deletePolicy(policyId: string){
    this.firestore.doc('policies/' + policyId).delete();
}

Step 6 - Creating a Component for Making CRUD Operations

After creating the model and service for creating, reading, updating and deleting insurance policies, you now need to create the component for testing our methods:

Using Angular CLI 8 run the following command to generate a component:

$ ng g c policy-list

Now, open the src/app/policy-list/policy-list.component.ts file and update it accordingly:

import { Component, OnInit } from '@angular/core';
import { PolicyService } from 'src/app/policy.service';
import { Policy } from 'src/app/policy.model';

@Component({
  selector: 'policy-list',
  templateUrl: './policy-list.component.html',
  styleUrls: ['./policy-list.component.css']
})
export class PolicyListComponent implements OnInit {

  policies: Policy[];
  constructor(private policyService: PolicyService) { }

  ngOnInit() {
    this.policyService.getPolicies().subscribe(data => {
      this.policies = data.map(e => {
        return {
          id: e.payload.doc.id,
          ...e.payload.doc.data()
        } as Policy;
      })
    });
  }

  create(policy: Policy){
      this.policyService.createPolicy(policy);
  }

  update(policy: Policy) {
    this.policyService.updatePolicy(policy);
  }

  delete(id: string) {
    this.policyService.deletePolicy(id);
  }
}

Updating the Component Template

Now let's update the component's template to display the insurance policies and also display buttons that can be used to create, update and delete policies:

Open the src/app/policy-list.component.html file and add the following HTML markup:

<table>
  <thead>
    <th>Number</th>
    <th>Created At</th>
    <th>Expire At</th>
    <th>Amount</th>
  </thead>
  <tbody>
    <tr *ngFor="let policy of policies">

      <td>{{policy.policyNumber}}</td>
      <td>{{policy.creationDate}}</td>
      <td>{{policy.expireDate}}</td>
      <td>{{policy.policyAmount}}</td>
      <td>
          <button (click)="delete(policy.id)">Delete</button>
      </td>
    </tr>
  </tbody>
</table>

Below the <table> markup, you can also add a form to create an insurance policy.

Conclusion

In this tutorial, we've seen by example how to add Firebase CRUD operations to your Angular 8 project that allow you to create, read, update and delete data from a Firestore database.