Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Angular and Firebase

Firebase is a comprehensive app development platform that provides a variety of tools and services to help you build high-quality apps. Integrating Firebase with Angular allows you to easily add features such as real-time databases, authentication, and hosting. This guide covers the basics of setting up and using Firebase with Angular.

Setting Up Firebase

First, create a Firebase project in the Firebase Console. After creating your project, you can add Firebase to your Angular application.

Installing Firebase and AngularFire

Install Firebase and AngularFire, the official Angular library for Firebase:

ng add @angular/fire

Follow the prompts to configure Firebase in your Angular project.

Configuring Firebase

Update your environment files with your Firebase project configuration:

// src/environments/environment.ts
export const environment = {
  production: false,
  firebase: {
    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',
    appId: 'YOUR_APP_ID',
    measurementId: 'YOUR_MEASUREMENT_ID'
  }
};

// src/environments/environment.prod.ts
export const environment = {
  production: true,
  firebase: {
    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',
    appId: 'YOUR_APP_ID',
    measurementId: 'YOUR_MEASUREMENT_ID'
  }
};

Initializing Firebase

Initialize Firebase in your Angular app module:

// src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { AngularFireDatabaseModule } from '@angular/fire/database';
import { environment } from '../environments/environment';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule,
    AngularFireDatabaseModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Using Firebase Authentication

Use Firebase Authentication to manage user sign-in and sign-out:

// src/app/auth.service.ts
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import firebase from 'firebase/app';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(private afAuth: AngularFireAuth) {}

  signInWithGoogle() {
    return this.afAuth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
  }

  signOut() {
    return this.afAuth.signOut();
  }
}

// src/app/app.component.ts
import { Component } from '@angular/core';
import { AuthService } from './auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(public authService: AuthService) {}

  signIn() {
    this.authService.signInWithGoogle();
  }

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

// src/app/app.component.html

Using Firebase Realtime Database

Use Firebase Realtime Database to read and write data:

// src/app/database.service.ts
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';

@Injectable({
  providedIn: 'root'
})
export class DatabaseService {
  constructor(private db: AngularFireDatabase) {}

  getItems() {
    return this.db.list('items').valueChanges();
  }

  addItem(item: any) {
    this.db.list('items').push(item);
  }
}

// src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { DatabaseService } from './database.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  items: Observable;

  constructor(private dbService: DatabaseService) {}

  ngOnInit() {
    this.items = this.dbService.getItems();
  }

  addItem(newItem: string) {
    this.dbService.addItem({ name: newItem });
  }
}

// src/app/app.component.html
  • {{ item.name }}

Hosting Your Angular App with Firebase

Use Firebase Hosting to deploy your Angular application:

Step 1: Install Firebase Tools

npm install -g firebase-tools

Step 2: Initialize Firebase in Your Project

firebase init

Follow the prompts to configure your project. Select Hosting and choose the dist/your-angular-app directory when asked for the public directory.

Step 3: Build Your Angular Application

ng build --prod

Step 4: Deploy to Firebase

firebase deploy

Key Points

  • Create a Firebase project in the Firebase Console.
  • Install Firebase and AngularFire using the Angular CLI.
  • Configure Firebase in your Angular application.
  • Use Firebase Authentication to manage user sign-in and sign-out.
  • Use Firebase Realtime Database to read and write data.
  • Use Firebase Hosting to deploy your Angular application.

Conclusion

Integrating Firebase with Angular provides a powerful platform for building and deploying web applications with features like authentication, real-time databases, and hosting. By following these steps, you can easily set up and use Firebase in your Angular projects. Happy coding!