How to integrate Firebase with Angular
firebase
35
angular
65
Male avatar

loveprogramming viết ngày 21/03/2021

https://grokonez.com/frontend/angular/how-to-integrate-firebase-with-angular-4

Firebase is a mobile and web application development platform developed by Google. We can build our apps very fast, without making complex back-end system. It helps to scale automatically, for even the largest apps. In this Angular Firebase tutorial, we're gonna go through the steps to integrate Firebase into Angular App with AngularFire2 4.0.

I. Technology

  • Angular
  • AngularFire2 4.0

    II. Step by Step

    1. Set up the Firebase Project

    Go to Firebase Console, login with your Google Account, then click on Add Project.

Enter Project name, select Country/Region:
angular-4-firebase-integration-create-firebase-project

Press CREATE PROJECT, browser turns into:
angular-4-firebase-integration-add-firebase-project

Click on Add Firebase to your Web App, a Popup will be shown:
angular-4-firebase-integration-copy-firebase-project-config

Save the information for later usage.

Choose Database in the left (list of Firebase features) -> Tab RULES, then change .read and .write values to true:
angular-4-firebase-integration-firebase-project-db-config

2. Install AngularFire2

Before installing AngularFire2, make sure that we have latest version of Angular-cli installed. The lowest compatible version is 1.x.x-beta.14. We also need Typings, and TypeScript.

So, if you don't have these things, try to install them:


npm install -g @angular/cli@latest
# or install locally
npm install @angular/cli --save-dev

npm install -g typings
npm install -g typescript

2.1 Create Angular project


ng new 
cd 

2.2 Install AngularFire2 and Firebase


npm install angularfire2 firebase --save

3. Use AngularFire2 in Angular Project

3.1 Add Firebase config to environments variable

Open /src/environments/environment.ts, add your Firebase configuration that we have saved when Popup window was shown:


export const environment = {
  production: false,
  firebase: {
    apiKey: 'xxx',
    authDomain: 'javasampleapproach-angular4.firebaseapp.com',
    databaseURL: 'https://javasampleapproach-angular4.firebaseio.com',
    projectId: 'javasampleapproach-angular4',
    storageBucket: 'javasampleapproach-angular4.appspot.com',
    messagingSenderId: 'xxx'
  }
};

3.2 Setup @NgModule

Open /src/app/app.module.ts, import AngularFireModule and other AngularFire2 modules if necessary. Don't forget specify Firebase configuration with AngularFireModule.initializeApp(firebaseConfig):


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

import {AngularFireModule} from 'angularfire2';
import {AngularFireDatabaseModule} from 'angularfire2/database';

import {environment} from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule, // for database
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule {}

3.3 Use AngularFire module in Angular component

Open /src/app/app.component.ts:


import {Component} from '@angular/core';

import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [AngularFireDatabase]
})

export class AppComponent {
  title = 'JavaSampleApproach';
  description = 'Angular4-Firebase Demo';

  itemValue = '';
  items: FirebaseListObservable;

  constructor(db: AngularFireDatabase) {
    this.items = db.list('/items');
  }

  onSubmit() {
    this.items.push({content: this.itemValue});
    this.itemValue = '';
  }
}

/src/app/app.component.html:

<div class="container-fluid">
    <div style="color: blue;">
        <h1>{{title}}</h1>
        <h3>{{description}}</h3>
    </div>

    <div style="width: 300px;">
        <form (ngSubmit)="onSubmit()">
            <div class="form-group">
                <label for="item">Item</label> <input type="text"
                    class="form-control" placeholder="Enter content..." id="item"
                    required [(ngModel)]="itemValue" name="item">
            </div>

            <div class="btn-group">
                <button type="submit" class="btn btn-success">Submit</button>
            </div>
        </form>
    </div>

    <h2>Content from Firebase</h2>
    <div class="col-md-3">
        <pre *ngFor="let item of items | async">{{item.content}}</.pre>
    </div>
</div>

III. Check Result

  • Open browser with url http://localhost:4200/, enter Item content.
    Item data displays immediately:
    angular-4-firebase-integration-firebase-result-add-item

  • Firebase Console Database:
    angular-4-firebase-integration-firebase-result-console-db

IV. Source Code

Angular4Firebase

https://grokonez.com/frontend/angular/how-to-integrate-firebase-with-angular-4

Bình luận


White
{{ comment.user.name }}
Bỏ hay Hay
{{comment.like_count}}
Male avatar
{{ comment_error }}
Hủy
   

Hiển thị thử

Chỉnh sửa

Male avatar

loveprogramming

451 bài viết.
79 người follow
Kipalog
{{userFollowed ? 'Following' : 'Follow'}}
Cùng một tác giả
Male avatar
1 0
Tutorial Link: (Link) (Ảnh) Django is a Pythonbased free and opensource web framework that follows the modeltemplateview architectural pattern. A...
loveprogramming viết 6 tháng trước
1 0
Male avatar
1 0
https://loizenai.com/angular11nodejspostgresqlcrudexample/ Angular 11 Node.js PostgreSQL Crud Example (Ảnh) Tutorial: “Angular 11 Node.js Postg...
loveprogramming viết 5 tháng trước
1 0
Male avatar
1 0
Angular Spring Boot jwt Authentication Example Github https://loizenai.com/angularspringbootjwt/ (Ảnh) Tutorial: ” Angular Spring Boot jwt Authe...
loveprogramming viết 5 tháng trước
1 0
Bài viết liên quan
Male avatar
0 0
https://grokonez.com/frontend/angular/angular4firebaseauthemailpasswordauthenticationwithangularfire2emaillogin Angular Firebase Auth Email/Passwo...
loveprogramming viết 2 tháng trước
0 0
White
26 11
Quá trình lột xác ngoạn mục của một hệ thống cổ lỗ sĩ khi được thiết kế cẩn thận: 1 usecase thành công của việc áp dụng triệt để các phương pháp xử...
Minh Monmen viết 11 tháng trước
26 11
{{like_count}}

kipalog

{{ comment_count }}

bình luận

{{liked ? "Đã kipalog" : "Kipalog"}}


Male avatar
{{userFollowed ? 'Following' : 'Follow'}}
451 bài viết.
79 người follow

 Đầu mục bài viết

Vẫn còn nữa! x

Kipalog vẫn còn rất nhiều bài viết hay và chủ đề thú vị chờ bạn khám phá!