iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 27
0
Modern Web

用Angular打造完整後台系列 第 27

day27 Firebase(一)

簡述

有些公司會在確任產品規格前,會先做些Demo到市場做水溫,
或是拿Demo去談合作,等確定是有利可圖的產品,
就會進行正式開發。

那大部分在做Demo時,多半會著重在畫面,
也就是美術跟前端的比例吃重些。

為了讓Demo可以做展示,很多會選擇Firebase來做 database
其實跟做json-server差不多,很多過濾跟組合都是在前端作業。

流程

  • firebase 簡述應用
  • firebase 基礎認知
  • Database 資料結構
  • firebase 物件操作

(一) firebase簡述應用

  • 請先到 https://console.firebase.google.com/ 登入會員並且新增專案。

  • 輸入自定義專案名稱,然後一直照著步驟下一步即可。

  • 等佈置完資源後,請選擇下方紅匡處 web
    firebaseview

  • 開始註冊應用程式的程序,並寫上暱稱,比如ngcms

  • 接下來會出現Firebase SDK,下面有一段:

var firebaseConfig = {
    apiKey: "AIzaSyAQszOv2H-*****",
    authDomain: "ngcms-*****.firebaseapp.com",
    databaseURL: "https://ngcms--*****..firebaseio.com",
    projectId: "ngcms--*****.",
    storageBucket: "ngcms--*****..appspot.com",
    messagingSenderId: "4337096-*****.",
    appId: "1:4337096-*****.:web:b4a18fc4fe94241c4a5b0e",
    measurementId: "G-YW3VR-*****."
  };

請記得copy下來,並且前往主控台。


(二) firebase基礎認知

我們將會使用 Firebase 裡面的Database
Database有兩種:

  • Cloud Firestore:Firebase主打
    擁有更強大的查詢和自動調整資源配置功能。

  • Realtime Database:可以替所有連結的用戶端即時儲存及同步處理資料。
    但是其實Cloud Firestore也做得到,加上有比較完整的查詢功能,
    所以本文都將以Cloud Firestore為主。

請建立 Cloud Firestore,並使用 測試模式 佈建。


(三) Database資料結構

day05 json-server 模擬與 Model 建置(一)
有提到json-server所用的 db.json

"admins": [
{
    "id": 1,
    "name": "admin01",
    "account": "admin01",
    "password": "admin01",
    "token": "bc6e113d26ce620066237d5e43f14690",
    "status": 1,
    "insertBy": 1,
    "inserted": 1565260416000,
    "updateBy": 1,
    "updated": 1565260416000
}
],
"powers": [
{
    "id": 1,
    "name": "admin"
},
{
    "id": 2,
    "name": "customer"
},
{
    "id": 3,
    "name": "product"
},
{
    "id": 4,
    "name": "order"
}
],
"holds": [
{
    "id": 1,
    "adminId": 1,
    "powerId": 1
},
{
    "id": 2,
    "adminId": 1,
    "powerId": 2
},
{
    "id": 3,
    "adminId": 1,
    "powerId": 3
},
{
    "id": 4,
    "adminId": 1,
    "powerId": 4
}
]

但是在 Firebase 裡所採取的是noSQL結構,
其實跟上面的json結構十分相像。

db1
db2

所謂的集合可以想成是List。
所謂的文件可以想成是List中的某一筆資料,
只是它的一筆資料拆成 id 跟其他內容。

不過這裡有個要注意的地方就是,
firebase的 idstring屬性。

有些比較複雜的系統,id都會用string,有時候是設計區分用的。
例如說商家的訂單號,可能會有來源號在裡面。

--

Database內容:

接下來就是把Demo的 db.json,轉成firebase的內容:

dbcontent

畫面中多了一個集合counters,是做流水號的記號,
因大部分的情況 id 都是自動流水號(number屬性)
所以為了做出自動流水號(後面會提及應用),所以如下所示:

dbcount

--

Demo運用

  • 首先先安裝@angular/fire
npm install firebase @angular/fire --save

非常多的網上教學文是使用 angularfire2
但我認為@angular/fire已經很完整,
沒有什麼必要要去下載 angularfire2

  • 在Angular中註冊firebase

還記得上面提到的,申請應用時firebase有給了一組。
那可以放在app.module.ts,也可以放在environments裡。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { AngularFireModule } from '@angular/fire';

const config = {
    apiKey: "AIzaSyAQszOv2H-*****",
    authDomain: "ngcms-*****.firebaseapp.com",
    databaseURL: "https://ngcms--*****..firebaseio.com",
    projectId: "ngcms--*****.",
    storageBucket: "ngcms--*****..appspot.com",
    messagingSenderId: "4337096-*****.",
    appId: "1:4337096-*****.:web:b4a18fc4fe94241c4a5b0e",
    measurementId: "G-YW3VR-*****."
};


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(config),
    AngularFirestoreModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

(四) firebase物件操作

很常看到並且需要知道的三種物件:

let afs: AngularFirestore //Cloud Firestore資料庫物件

let afc = this.afs.collection("admins")  //AngularFirestoreCollection

let afd = this.afs.collection("admins").doc(id)//AngularFirestoreDocument

AngularFirestoreCollection是操作集合
AngularFirestoreDocument是操作文件

簡單說就是:
Collection、Document其實可以看成指向位置,
一個是list物件,一個是list的某一筆物件,
所以要show list 資料以及篩選資料,就會使用 Collection

在firebase裡最右邊的欄位會出現集合,也就是說文件裡面可以有集合。

Select:

先來說說搜尋

this.afs.collection("admins")

this.afs.collection("admins",ref => ref.where('name', '==', 'john'))

this.afs.collection("admins",ref => ref.where('name', '==', 'john')
                                        .where('age', '>=', '20'))

如上述例子所看到的,
collection的第二參數放的是 query 條件

--

如果要找某一筆資料:

let afd = this.afs.collection("admins").doc(1)

let afd = this.afs.doc("admins/1")

--

若是找全部資料,物件的回應值有 valueChangessnapshotChanges

valueChanges:除了id以外的資料都有。
snapshotChanges:完整資料包含id。

   this.arrs.valueChanges()
   this.arrs
    .snapshotChanges()
    .pipe(
        map(actions => actions.map(a => {
            const data = a.payload.doc.data();
            const id = a.payload.doc.id;
            return { id, ...data };
        }))
    );

--

單找某筆資料,物件的回應值有 valueChanges

    let afd = afs.doc('admins/1');
    this.admin = afd.valueChanges();

當要找某筆資料也就代表知道id,所以在使用 Document 時,
請使用valueChanges()


Insert:

以下是 Collection、Document 各自新增的寫法:

this.afs.collection("admins").add(data)
this.afs.collection("admins").doc(1).set(data)

id通常是新增時firebase亂數產生的,當然也可以直接指定。
如上面的doc(1),如果不存在id1則會新增id1。


Update:

this.afs.collection("admins").doc(1).update(data)

Delete:

this.afs.collection("admins").doc(1).delete(data)

update 跟 delete 都是要帶id進去才能操作,
所以一定是Document物件。


上一篇
day26 IndexModule
下一篇
day28 Firebase(二)應用
系列文
用Angular打造完整後台30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言