AngularFire Web 代碼實驗室

1. 概述

在此 Codelab 中,您將學習如何使用AngularFire通過使用 Firebase 產品和服務實現和部署聊天客戶端來創建 Web 應用程序。

angularfire-2.png

你將學到什麼

  • 使用 Angular 和 Firebase 構建 Web 應用。
  • 使用 Cloud Firestore 和 Cloud Storage for Firebase 同步數據。
  • 使用 Firebase 身份驗證對您的用戶進行身份驗證。
  • 在 Firebase 託管上部署您的 Web 應用。
  • 使用 Firebase 雲消息傳遞發送通知。
  • 收集您的網絡應用程序的性能數據。

你需要什麼

  • 您選擇的 IDE/文本編輯器,例如WebStormAtomSublimeVS Code
  • 包管理器npm ,通常隨Node.js一起提供
  • 終端/控制台
  • 您選擇的瀏覽器,例如 Chrome
  • Codelab的示例代碼(有關如何獲取代碼,請參閱Codelab的下一步。)

2. 獲取示例代碼

從命令行克隆 Codelab 的GitHub 存儲庫

git clone https://github.com/firebase/codelab-friendlychat-web

或者,如果您沒有安裝 git,則可以將存儲庫下載為 ZIP 文件

導入入門應用程序

使用 IDE,從克隆的存儲庫中打開或導入 📁 angularfire-start目錄。這個 📁 angularfire-start目錄包含 Codelab 的起始代碼,它將是一個功能齊全的聊天 Web 應用程序。

3. 創建並設置 Firebase 項目

創建 Firebase 項目

  1. 登錄Firebase
  2. 在 Firebase 控制台中,單擊添加項目,然後將您的 Firebase 項目命名為FriendlyChat 。請記住您的 Firebase 項目的項目 ID。
  3. 取消選中為此項目啟用 Google Analytics
  4. 單擊“創建項目”

您要構建的應用程序使用可用於網絡應用的 Firebase 產品:

  • Firebase 身份驗證可輕鬆允許您的用戶登錄您的應用。
  • Cloud Firestore將結構化數據保存在雲上,並在數據發生變化時獲得即時通知。
  • Cloud Storage for Firebase將文件保存在雲中。
  • Firebase Hosting用於託管和服務您的資產。
  • Firebase Cloud Messaging用於發送推送通知並顯示瀏覽器彈出通知。
  • Firebase 性能監控,用於收集應用的用戶性能數據。

其中一些產品需要特殊配置或需要使用 Firebase 控制台啟用。

將 Firebase Web 應用添加到項目中

  1. 單擊網絡圖標58d6543a156e56f9.png創建一個新的 Firebase Web 應用。
  2. 使用暱稱“Friendly Chat”註冊應用程序,然後選中“同時為此應用程序設置 Firebase 託管”旁邊的框。單擊註冊應用程序
  3. 在下一步中,您將看到一個配置對象。僅將 JS 對象(而不是周圍的 HTML)複製到firebase-config.js

註冊網絡應用程序截圖

啟用 Google登錄以進行 Firebase 身份驗證

要允許用戶使用其 Google 帳戶登錄網絡應用程序,您將使用Google登錄方法。

您需要啟用Google登錄:

  1. 在 Firebase 控制台中,找到左側面板中的“構建”部分。
  2. 單擊“身份驗證” ,然後單擊“登錄方法”選項卡(或單擊此處直接轉到此處)。
  3. 啟用Google登錄提供商,然後單擊“保存”
  4. 將應用程序面向公眾的名稱設置為“友好聊天” ,然後從下拉菜單中選擇項目支持電子郵件
  5. Google Cloud Console中配置 OAuth 同意屏幕並添加徽標:

d89fb3873b5d36ae.png

啟用 Cloud Firestore

Web 應用程序使用Cloud Firestore保存聊天消息並接收新的聊天消息。

您需要啟用 Cloud Firestore:

  1. 在 Firebase 控制台的“構建”部分中,單擊Firestore 數據庫
  2. 單擊 Cloud Firestore 窗格中的創建數據庫

729991a081e7cd5.png

  1. 選擇“以測試模式啟動”選項,然後在閱讀有關安全規則的免責聲明後單擊“下一步”

測試模式保證您在開發過程中可以自由地寫入數據庫。稍後您將在此 Codelab 中使我們的數據庫更加安全。

77e4986cbeaf9dee.png

  1. 設置 Cloud Firestore 數據的存儲位置。您可以將其保留為默認值或選擇離您較近的區域。單擊“完成”以配置 Firestore。

9f2bb0d4e7ca49c7.png

啟用雲存儲

該 Web 應用使用 Cloud Storage for Firebase 來存儲、上傳和共享圖片。

您需要啟用雲存儲:

  1. 在 Firebase 控制台的“構建”部分中,單擊“存儲”
  2. 如果沒有“開始”按鈕,則表示雲存儲已啟用,您無需執行以下步驟。
  3. 單擊開始
  4. 閱讀有關 Firebase 項目安全規則的免責聲明,然後單擊“下一步”

使用默認安全規則,任何經過身份驗證的用戶都可以向 Cloud Storage 寫入任何內容。稍後,您將在此 Codelab 中使我們的存儲更加安全。

62f1afdcd1260127.png

  1. 預先選擇的 Cloud Storage 位置與您為 Cloud Firestore 數據庫選擇的區域相同。單擊“完成”完成設置。

1d7f49ebaddb32fc.png

4.安裝Firebase命令行界面

Firebase 命令行界面 (CLI) 允許您使用 Firebase 託管在本地提供您的 Web 應用程序,以及將您的 Web 應用程序部署到 Firebase 項目。

  1. 通過運行以下 npm 命令安裝 CLI:
npm -g install firebase-tools
  1. 通過運行以下命令驗證 CLI 是否已正確安裝:
firebase --version

確保 Firebase CLI 的版本為 v4.1.0 或更高版本。

  1. 通過運行以下命令授權 Firebase CLI:
firebase login

您已設置 Web 應用模板,以從應用的本地目錄(您之前在 Codelab 中克隆的存儲庫)中提取應用的 Firebase 託管配置。但要提取配置,您需要將應用程序與 Firebase 項目關聯。

  1. 確保您的命令行正在訪問應用程序的本地angularfire-start目錄。
  2. 通過運行以下命令將您的應用與 Firebase 項目關聯:
firebase use --add
  1. 出現提示時,選擇您的項目 ID ,然後為您的 Firebase 項目指定一個別名。

如果您有多個環境(生產、登台等),則別名很有用。但是,對於此 Codelab,我們只使用default別名。

  1. 按照命令行上的其餘說明進行操作。

5.安裝AngularFire

在運行項目之前,請確保已設置 Angular CLI 和 AngularFire。

  1. 在控制台中,運行以下命令:
npm install -g @angular/cli
  1. 然後,在angularfire-start目錄的控制台中,運行以下 Angular CLI 命令:
ng add @angular/fire

這將為您的項目安裝所有必需的依賴項。

  1. 出現提示時,選擇在 Firebase 控制台中設置的功能( ng deploy -- hostingAuthenticationFirestoreCloud Functions (callable)Cloud MessagingCloud Storage ),然後按照控制台上的提示進行操作。

6. 在本地運行入門應用程序

現在您已導入並配置了項目,您已準備好首次運行 Web 應用程序。

  1. angularfire-start目錄的控制台中,運行以下 Firebase CLI 命令:
firebase emulators:start
  1. 您的命令行應顯示以下響應:
✔  hosting: Local server: http://localhost:5000

您正在使用Firebase 託管模擬器在本地為我們的應用程序提供服務。現在應該可以從http://localhost:5000訪問該 Web 應用程序。提供位於src子目錄下的所有文件。

  1. 使用瀏覽器,在http://localhost:5000打開您的應用程序。

您應該會看到FriendlyChat應用程序的UI,它(尚未!)運行:

AngularFire-2.png

該應用程序現在無法執行任何操作,但在您的幫助下,很快就會!到目前為止,您只為您設計了 UI。

現在讓我們建立一個實時聊天!

7. 導入並配置 Firebase

配置 Firebase

您需要配置 Firebase SDK 以告訴它您正在使用哪個 Firebase 項目。

  1. 轉到Firebase 控制台中的項目設置
  2. 在“您的應用程序”卡中,選擇您需要配置對象的應用程序的暱稱。
  3. 從 Firebase SDK 代碼段窗格中選擇“配置”。

你會發現已經為你生成了一個環境文件/angularfire-start/src/environments/environment.ts

  1. 複製配置對象片段,然後將其添加到angularfire-start/src/firebase-config.js

環境.ts

export const environment = {
  firebase: {
    apiKey: "API_KEY",
    authDomain: "PROJECT_ID.firebaseapp.com",
    databaseURL: "https://PROJECT_ID.firebaseio.com",
    projectId: "PROJECT_ID",
    storageBucket: "PROJECT_ID.appspot.com",
    messagingSenderId: "SENDER_ID",
    appId: "APP_ID",
    measurementId: "G-MEASUREMENT_ID",
  },
};

導入 AngularFire

您會發現您在控制台中選擇的功能已自動路由到/angularfire-start/src/app/app.module.ts文件中。這允許您的應用使用 Firebase 特性和功能。但是,要在本地環境中進行開發,您需要連接它們才能使用模擬器套件。

  1. /angularfire-start/src/app/app.module.ts中,找到imports部分,並修改提供的函數以在非生產環境中連接到模擬器套件。
// ...

import { provideAuth,getAuth, connectAuthEmulator } from '@angular/fire/auth';
import { provideFirestore,getFirestore, connectFirestoreEmulator } from '@angular/fire/firestore';
import { provideFunctions,getFunctions, connectFunctionsEmulator } from '@angular/fire/functions';
import { provideMessaging,getMessaging } from '@angular/fire/messaging';
import { provideStorage,getStorage, connectStorageEmulator } from '@angular/fire/storage';

// ...

provideFirebaseApp(() => initializeApp(environment.firebase)),
provideAuth(() => {
    const auth = getAuth();
    if (location.hostname === 'localhost') {
        connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });
    }
    return auth;
}),
provideFirestore(() => {
    const firestore = getFirestore();
    if (location.hostname === 'localhost') {
        connectFirestoreEmulator(firestore, '127.0.0.1', 8080);
    }
    return firestore;
}),
provideFunctions(() => {
    const functions = getFunctions();
    if (location.hostname === 'localhost') {
        connectFunctionsEmulator(functions, '127.0.0.1', 5001);
    }
    return functions;
}),
provideStorage(() => {
    const storage = getStorage();
    if (location.hostname === 'localhost') {
        connectStorageEmulator(storage, '127.0.0.1', 5001);
    }
    return storage;
}),
provideMessaging(() => {
    return getMessaging();
}),

// ...

應用程序模塊.ts

在此 Codelab 中,您將使用 Firebase 身份驗證、Cloud Firestore、雲存儲、雲消息傳遞和性能監控,因此您將導入它們的所有庫。在您未來的應用中,請確保您僅導入所需的 Firebase 部分,以縮短應用的加載時間。

8. 設置用戶登錄

AngularFire 現在應該可以使用了,因為它是在app.module.ts中導入並初始化的。您現在將使用Firebase Authentication實現用戶登錄。

使用 Google 登錄對您的用戶進行身份驗證

在應用程序中,當用戶單擊“使用 Google 登錄”按鈕時,就會觸發login功能。 (您已經進行了設置!)對於此 Codelab,您希望授權 Firebase 使用 Google 作為身份提供商。您將使用彈出窗口,但 Firebase 還提供其他幾種方法

  1. angularfire-start目錄的子目錄/src/app/services/中,打開chat.service.ts
  2. 找到login功能。
  3. 將整個函數替換為以下代碼。

聊天服務.ts

// Signs-in Friendly Chat.
login() {
    signInWithPopup(this.auth, this.provider).then((result) => {
        const credential = GoogleAuthProvider.credentialFromResult(result);
        this.router.navigate(['/', 'chat']);
        return credential;
    })
}

當用戶單擊“註銷logout功能。

  1. 返回文件src/app/services/chat.service.ts
  2. 找到函數logout
  3. 將整個函數替換為以下代碼。

聊天服務.ts

// Logout of Friendly Chat.
logout() {
    signOut(this.auth).then(() => {
        this.router.navigate(['/', 'login'])
        console.log('signed out');
    }).catch((error) => {
        console.log('sign out error: ' + error);
    })
}

跟踪身份驗證狀態

要相應地更新我們的 UI,您需要一種方法來檢查用戶是否登錄或註銷。使用 Firebase 身份驗證,您可以檢索每次身份驗證狀態更改時將觸發的用戶狀態的可觀察值。

  1. 返回文件src/app/services/chat.service.ts
  2. 找到變量賦值user$
  3. 將整個作業替換為以下代碼。

聊天服務.ts

// Observable user
user$ = user(this.auth);

上面的代碼調用 AngularFire 函數user ,它返回一個可觀察的用戶。每次身份驗證狀態更改時(當用戶登錄或註銷時)都會觸發它。此時,您將更新 UI 以進行重定向、在標題導航中顯示用戶等。所有這些 UI 部分都已實現。

測試登錄應用程序

  1. 如果您的應用程序仍在運行,請在瀏覽器中刷新您的應用程序。否則,請在命令行上運行firebase emulators:start以開始從http://localhost:5000提供應用程序,然後在瀏覽器中打開它。
  2. 使用登錄按鈕和您的 Google 帳戶登錄該應用程序。如果您看到一條錯誤消息,指出auth/operation-not-allowed ,請檢查以確保您在 Firebase 控制台中啟用了 Google Sign-in 作為身份驗證提供程序。
  3. 登錄後,應顯示您的個人資料圖片和用戶名: angularfire-3.png

9. 將消息寫入 Cloud Firestore

在本部分中,您將向 Cloud Firestore 寫入一些數據,以便填充應用的 UI。這可以使用Firebase 控制台手動完成,但您將在應用程序本身中執行此操作以演示基本的 Cloud Firestore 寫入。

數據模型

Cloud Firestore 數據分為集合、文檔、字段和子集合。您將把聊天的每條消息作為文檔存儲在名為messages頂級集合中。

688d7bc5fb662b57.png

將消息添加到 Cloud Firestore

要存儲用戶編寫的聊天消息,您將使用Cloud Firestore

在本部分中,您將添加用戶向數據庫寫入新消息的功能。用戶單擊“發送”按鈕將觸發下面的代碼片段。它將包含消息字段內容的消息對象添加到messages集合中的 Cloud Firestore 實例。 add()方法將具有自動生成的 ID 的新文檔添加到集合中。

  1. 返回文件src/app/services/chat.service.ts
  2. 找到函數addMessage
  3. 將整個函數替換為以下代碼。

聊天服務.ts

// Adds a text or image message to Cloud Firestore.
addMessage = async(textMessage: string | null, imageUrl: string | null): Promise<void | DocumentReference<DocumentData>> => {
    let data: any;
    try {
      this.user$.subscribe(async (user) => 
      { 
        if(textMessage && textMessage.length > 0) {
          data =  await addDoc(collection(this.firestore, 'messages'), {
            name: user?.displayName,
            text: textMessage,
            profilePicUrl: user?.photoURL,
            timestamp: serverTimestamp(),
            uid: user?.uid
          })}
          else if (imageUrl && imageUrl.length > 0) {
            data =  await addDoc(collection(this.firestore, 'messages'), {
              name: user?.displayName,
              imageUrl: imageUrl,
              profilePicUrl: user?.photoURL,
              timestamp: serverTimestamp(),
              uid: user?.uid
            });
          }
          return data;
        }
      );
    }
    catch(error) {
      console.error('Error writing new message to Firebase Database', error);
      return;
    }
}

測試發送消息

  1. 如果您的應用程序仍在運行,請在瀏覽器中刷新您的應用程序。否則,請在命令行上運行firebase emulators:start以開始從http://localhost:5000提供應用程序,然後在瀏覽器中打開它。
  2. 登錄後,輸入一條消息,例如“嘿那裡!”,然後單擊“發送” 。這會將消息寫入 Cloud Firestore。但是,您還不會在實際的 Web 應用程序中看到數據,因為您仍然需要實現數據檢索(Codelab 的下一部分)。
  3. 您可以在 Firebase 控制台中看到新添加的消息。打開您的模擬器套件 UI。在“構建”部分下,單擊Firestore 數據庫(或單擊此處,您應該會看到包含新添加消息的消息集合:

6812efe7da395692.png

10. 閱讀消息

同步消息

要讀取應用程序中的消息,您需要添加一個在數據更改時觸發的可觀察對象,然後創建一個顯示新消息的 UI 元素。

您將添加代碼來偵聽來自應用程序的新添加的消息。在此代碼中,您將檢索messages集合的快照。您將僅顯示聊天的最後 12 條消息,以避免加載時顯示很長的歷史記錄。

  1. 返回文件src/app/services/chat.service.ts
  2. 找到函數loadMessages
  3. 將整個函數替換為以下代碼。

聊天服務.ts

// Loads chat message history and listens for upcoming ones.
loadMessages = () => {
  // Create the query to load the last 12 messages and listen for new ones.
  const recentMessagesQuery = query(collection(this.firestore, 'messages'), orderBy('timestamp', 'desc'), limit(12));
  // Start listening to the query.
  return collectionData(recentMessagesQuery);
}

要偵聽數據庫中的消息,您可以使用collection函數在集合上創建查詢,以指定要偵聽的數據位於哪個集合中。在上面的代碼中,您正在偵聽messages中的更改集合,這是存儲聊天消息的地方。您還可以通過使用limit(12)僅偵聽最後 12 條消息並使用orderBy('timestamp', 'desc')按日期對消息進行排序來應用限制,以獲取 12 條最新消息。

collectionData函數在底層使用快照。當與查詢匹配的文檔發生任何更改時,將觸發回調函數。這可能是因為消息被刪除、修改或添加。您可以在Cloud Firestore 文檔中閱讀有關此內容的更多信息。

測試同步消息

  1. 如果您的應用程序仍在運行,請在瀏覽器中刷新您的應用程序。否則,請在命令行上運行firebase emulators:start以開始從http://localhost:5000提供應用程序,然後在瀏覽器中打開它。
  2. 您之前在數據庫中創建的消息應顯示在FriendlyChat UI 中(見下文)。隨意寫新消息;它們應該立即出現。
  3. (可選)您可以嘗試直接在模擬器套件的Firestore部分中手動刪除、修改或添加新消息;任何更改都應反映在 UI 中。

恭喜!您正在應用中閱讀 Cloud Firestore 文檔!

AngularFire-2.png

11.發送圖像

您現在將添加共享圖像的功能。

雖然 Cloud Firestore 適合存儲結構化數據,但 Cloud Storage 更適合存儲文件。 Cloud Storage for Firebase是一種文件/blob 存儲服務,您將使用它來存儲用戶使用我們的應用共享的任何圖像。

將圖像保存到雲存儲

在此 Codelab 中,您已經添加了一個可觸發文件選擇器對話框的按鈕。選擇文件後,將調用saveImageMessage函數,您可以獲得對所選文件的引用。 saveImageMessage函數完成以下任務:

  1. 在聊天源中創建“佔位符”聊天消息,以便用戶在您上傳圖像時看到“正在加載”動畫。
  2. 將圖像文件上傳到 Cloud Storage 的以下路徑: /<uid>/<file_name>
  3. 生成圖像文件的公共可讀 URL。
  4. 使用新上傳的圖像文件的 URL 代替臨時加載圖像來更新聊天消息。

現在您將添加發送圖像的功能:

  1. 返回文件src/index.js
  2. 找到函數saveImageMessage
  3. 將整個函數替換為以下代碼。

索引.js

// Saves a new message containing an image in Firebase.
// This first saves the image in Firebase storage.
saveImageMessage = async(file: any) => {
  try {
    // 1 - You add a message with a loading icon that will get updated with the shared image.
    const messageRef = await this.addMessage(null, this.LOADING_IMAGE_URL);

    // 2 - Upload the image to Cloud Storage.
    const filePath = `${this.auth.currentUser?.uid}/${file.name}`;
    const newImageRef = ref(this.storage, filePath);
    const fileSnapshot = await uploadBytesResumable(newImageRef, file);
    
    // 3 - Generate a public URL for the file.
    const publicImageUrl = await getDownloadURL(newImageRef);

    // 4 - Update the chat message placeholder with the image's URL.
    messageRef ?
    await updateDoc(messageRef,{
      imageUrl: publicImageUrl,
      storageUri: fileSnapshot.metadata.fullPath
    }): null;
  } catch (error) {
    console.error('There was an error uploading a file to Cloud Storage:', error);
  }
}

測試發送圖像

  1. 如果您的應用程序仍在運行,請在瀏覽器中刷新您的應用程序。否則,請在命令行上運行firebase emulators:start以開始從http://localhost:5000提供應用程序,然後在瀏覽器中打開它。
  2. 登錄後,點擊左下角圖片上傳按鈕angularfire-4.png並使用文件選擇器選擇圖像文件。如果您正在尋找圖像,請隨意使用這張漂亮的咖啡杯圖片
  3. 應用程序的 UI 中應出現一條新消息,其中包含您選擇的圖像: AngularFire-2.png

如果您在未登錄的情況下嘗試添加圖像,您應該會看到一條錯誤消息,告訴您必須登錄才能添加圖像。

12.顯示通知

您現在將添加對瀏覽器通知的支持。當聊天中發布新消息時,該應用程序將通知用戶。 Firebase Cloud Messaging (FCM) 是一種跨平台消息傳遞解決方案,可讓您免費可靠地傳遞消息和通知。

添加 FCM 服務工作人員

Web 應用程序需要一個Service Worker來接收和顯示 Web 通知。

添加 AngularFire 時應該已經設置了消息提供程序,請確保/angularfire-start/src/app/app.module.ts的導入部分中存在以下代碼

provideMessaging(() => {
    return getMessaging();
}),

應用程序/應用程序模塊.ts

Service Worker 只需加載並初始化 Firebase Cloud Messaging SDK,它將負責顯示通知。

獲取 FCM 設備令牌

當設備或瀏覽器上啟用通知時,您將獲得一個設備令牌。您可以使用此設備令牌向特定設備或特定瀏覽器發送通知。

當用戶登錄時,您調用saveMessagingDeviceToken函數。您可以在此處從瀏覽器獲取FCM 設備令牌並將其保存到 Cloud Firestore。

聊天服務.ts

  1. 找到函數saveMessagingDeviceToken
  2. 將整個函數替換為以下代碼。

聊天服務.ts

// Saves the messaging device token to Cloud Firestore.
saveMessagingDeviceToken= async () => {
    try {
      const currentToken = await getToken(this.messaging);
      if (currentToken) {
        console.log('Got FCM device token:', currentToken);
        // Saving the Device Token to Cloud Firestore.
        const tokenRef = doc(this.firestore, 'fcmTokens', currentToken);
        await setDoc(tokenRef, { uid: this.auth.currentUser?.uid });
 
        // This will fire when a message is received while the app is in the foreground.
        // When the app is in the background, firebase-messaging-sw.js will receive the message instead.
        onMessage(this.messaging, (message) => {
          console.log(
            'New foreground notification from Firebase Messaging!',
            message.notification
          );
        });
      } else {
        // Need to request permissions to show notifications.
        this.requestNotificationsPermissions();
      }
    } catch(error) {
      console.error('Unable to get messaging token.', error);
    };
}

但是,此代碼最初不起作用。為了讓您的應用能夠檢索設備令牌,用戶需要授予您的應用顯示通知的權限(Codelab 的下一步)。

請求顯示通知的權限

當用戶尚未授予您的應用顯示通知的權限時,您將不會獲得設備令牌。在這種情況下,您調用requestPermission()方法,該方法將顯示一個瀏覽器對話框,請求此權限(在支持的瀏覽器中)。

8b9d0c66dc36153d.png

  1. 返回文件src/app/services/chat.service.ts
  2. 找到函數requestNotificationsPermissions
  3. 將整個函數替換為以下代碼。

聊天服務.ts

// Requests permissions to show notifications.
requestNotificationsPermissions = async () => {
    console.log('Requesting notifications permission...');
    const permission = await Notification.requestPermission();
    
    if (permission === 'granted') {
      console.log('Notification permission granted.');
      // Notification permission granted.
      await this.saveMessagingDeviceToken();
    } else {
      console.log('Unable to get permission to notify.');
    }
}

獲取您的設備令牌

  1. 如果您的應用程序仍在運行,請在瀏覽器中刷新您的應用程序。否則,請在命令行上運行firebase emulators:start以開始從http://localhost:5000提供應用程序,然後在瀏覽器中打開它。
  2. 登錄後,應出現通知權限對話框: bd3454e6dbfb6723.png
  3. 單擊“允許”
  4. 打開瀏覽器的 JavaScript 控制台。您應該看到以下消息: Got FCM device token: cWL6w:APA91bHP...4jDPL_A-wPP06GJp1OuekTaTZI5K2Tu
  5. 複製您的設備令牌。您將在 Codelab 的下一階段需要它。

向您的設備發送通知

現在您已擁有設備令牌,您可以發送通知。

  1. 打開Firebase 控制台的“雲消息傳遞”選項卡
  2. 點擊“新通知”
  3. 輸入通知標題和通知文本。
  4. 在屏幕右側,單擊“發送測試消息”
  5. 輸入您從瀏覽器的 JavaScript 控制台複製的設備令牌,然後單擊加號 (“+”)
  6. 點擊“測試”

如果您的應用程序位於前台,您將在 JavaScript 控制台中看到通知。

如果您的應用程序在後台運行,則瀏覽器中應顯示一條通知,如下例所示:

de79e8638a45864c.png

13.Cloud Firestore 安全規則

查看數據庫安全規則

Cloud Firestore 使用特定的規則語言來定義訪問權限、安全性和數據驗證。

在本 Codelab 開始時設置 Firebase 項目時,您選擇使用“測試模式”默認安全規則,以便不限制對數據存儲區的訪問。在Firebase 控制台的“數據庫”部分的“規則”選項卡中,您可以查看和修改這些規則。

現在,您應該看到默認規則,這些規則不限制對數據存儲的訪問。這意味著任何用戶都可以讀取和寫入數據存儲中的任何集合。

rules_version = '2';

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

您將使用以下規則更新規則以限制事物:

firestore.規則

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    // Messages:
    //   - Anyone can read.
    //   - Authenticated users can add and edit messages.
    //   - Validation: Check name is same as auth token and text length below 300 char or that imageUrl is a URL.
    //   - Deletes are not allowed.
    match /messages/{messageId} {
      allow read;
      allow create, update: if request.auth != null
                    && request.resource.data.name == request.auth.token.name
                    && (request.resource.data.text is string
                      && request.resource.data.text.size() <= 300
                      || request.resource.data.imageUrl is string
                      && request.resource.data.imageUrl.matches('https?://.*'));
      allow delete: if false;
    }
    // FCM Tokens:
    //   - Anyone can write their token.
    //   - Reading list of tokens is not allowed.
    match /fcmTokens/{token} {
      allow read: if false;
      allow write;
    }
  }
}

安全規則應自動更新到您的模擬器套件。

查看雲存儲安全規則

Cloud Storage for Firebase 使用特定的規則語言來定義訪問權限、安全性和數據驗證。

在本 Codelab 開始時設置 Firebase 項目時,您選擇使用默認的 Cloud Storage 安全規則,該規則僅允許經過身份驗證的用戶使用 Cloud Storage。在Firebase 控制台的“存儲”部分的“規則”選項卡中,您可以查看和修改規則。您應該會看到默認規則,該規則允許任何登錄用戶讀取和寫入存儲桶中的任何文件。

rules_version = '2';

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}

您將更新規則以執行以下操作:

  • 允許每個用戶僅寫入自己的特定文件夾
  • 允許任何人從 Cloud Storage 讀取
  • 確保上傳的文件是圖片
  • 將可上傳的圖像大小限制為最大 5 MB

這可以使用以下規則來實現:

存儲規則

rules_version = '2';

// Returns true if the uploaded file is an image and its size is below the given number of MB.
function isImageBelowMaxSize(maxSizeMB) {
  return request.resource.size < maxSizeMB * 1024 * 1024
      && request.resource.contentType.matches('image/.*');
}

service firebase.storage {
  match /b/{bucket}/o {
    match /{userId}/{messageId}/{fileName} {
      allow write: if request.auth != null && request.auth.uid == userId && isImageBelowMaxSize(5);
      allow read;
    }
  }
}

14. 使用 Firebase 託管部署您的應用

Firebase 提供託管服務來為您的資產和 Web 應用提供服務。您可以使用 Firebase CLI 將文件部署到 Firebase 託管。在部署之前,您需要在firebase.json文件中指定應部署哪些本地文件。對於此 Codelab,您已經為您完成了此操作,因為在此 Codelab 期間需要執行此步驟來提供我們的文件。託管設置在hosting屬性下指定:

firebase.json

{
  // If you went through the "Cloud Firestore Security Rules" step.
  "firestore": {
    "rules": "firestore.rules"
  },
  // If you went through the "Storage Security Rules" step.
  "storage": {
    "rules": "storage.rules"
  },
  "hosting": {
    "public": "./public"
  }
}

這些設置告訴 CLI 您要部署./public目錄中的所有文件 ( "public": "./public" )。

  1. 確保您的命令行正在訪問應用程序的本地angularfire-start目錄。
  2. 通過運行以下命令將文件部署到 Firebase 項目:
ng deploy

然後選擇 Firebase 選項,並按照命令行中的提示進行操作。

  1. 控制台應顯示以下內容:
=== Deploying to 'friendlychat-1234'...

i  deploying firestore, storage, hosting
i  storage: checking storage.rules for compilation errors...
✔  storage: rules file storage.rules compiled successfully
i  firestore: checking firestore.rules for compilation errors...
✔  firestore: rules file firestore.rules compiled successfully
i  storage: uploading rules storage.rules...
i  firestore: uploading rules firestore.rules...
i  hosting[friendlychat-1234]: beginning deploy...
i  hosting[friendlychat-1234]: found 8 files in ./public
✔  hosting[friendlychat-1234]: file upload complete
✔  storage: released rules storage.rules to firebase.storage/friendlychat-1234.appspot.com
✔  firestore: released rules firestore.rules to cloud.firestore
i  hosting[friendlychat-1234]: finalizing version...
✔  hosting[friendlychat-1234]: version finalized
i  hosting[friendlychat-1234]: releasing new version...
✔  hosting[friendlychat-1234]: release complete

✔  Deploy complete!

Project Console: https://console.firebase.google.com/project/friendlychat-1234/overview
Hosting URL: https://friendlychat-1234.firebaseapp.com
  1. 訪問您的 Web 應用程序,該應用程序現在已在您自己的兩個 Firebase 子域中使用 Firebase 託管完全託管在全球 CDN 上:
  • https://<firebase-projectId>.firebaseapp.com
  • https://<firebase-projectId>.web.app

或者,您可以在命令行中運行firebase open hosting:site

請訪問文檔以詳細了解Firebase 託管的工作原理

轉到項目的 Firebase 控制台託管部分,查看有用的託管信息和工具,包括部署歷史記錄、回滾到應用程序先前版本的功能以及設置自定義域的工作流程。

15. 恭喜!

您已使用 Firebase 構建了實時聊天 Web 應用程序!

您所涵蓋的內容

  • Firebase 身份驗證
  • 雲Firestore
  • 適用於雲存儲的 Firebase SDK
  • Firebase 雲消息傳遞
  • Firebase 性能監控
  • Firebase 託管

下一步

了解更多