簡體   English   中英

如何將 Firebase 快照 object 分配給 Angular 類型

[英]How to assign a Firebase snapshot object to an Angular type

我在 Angular 中創建了一個客戶服務,以從 Firebase 實時數據庫中獲取客戶列表,如下所示:

  getCustomers() {
       return this.db.list('/customers', ref => ref.orderByChild('name')).snapshotChanges(); }

這成功返回了一個 JSON 數組。

然后我定義了客戶接口如下:

export interface Customer {
  name: string;
  address: string;
  type: string;
  phone: string;}

現在,在組件中,我正在嘗試訪問客戶信息,如下所示:

customers: Customer[];
subscription: Subscription;
constructor(private customerService: CustomerService) {
this.subscription = this.customerService.getCustomers().subscribe(customers => this.customers = customers.map(c => c.payload.val()));

}

這給了我一個編譯錯誤“ Type Unknow is not assignable to type Customer[] ”。 我的問題是:

  1. 將 payload().val() JSON output 轉換為客戶類型的最佳方法是什么?
  2. 如何訪問每條記錄的密鑰?(這是我的頁面所必需的)。

提前謝謝了。

------ 基於 Le_Buzz 的建議和指導,更新了工作解決方案 ------

//首先我更新了客戶界面以包含字段“key”,如下所示:

export interface Customer {
  key: string;
  name: string;
  address: string;
  type: string;
  phone: string;}

//聲明customers數組如下:

customers: Customer[] = [];

//然后訂閱 Observable 如下:

subscription: Subscription;
  this.subscription = this.customerService.getCustomers().subscribe(cus => {
  cus.forEach(cus => {
    const values = cus.payload.val();
    const key = cus.payload.key;
    this.customers.push({ name: values["name"], key: key, address: values["address"], type: values["type"], phone: values["phone"] })
  })
}) 

首先,我建議你把firebase中的客戶信息變成一個數組,然后用這個數組來構建客戶object(可能有更簡潔的方法,但這是我現在能想到的)。 至於第二個問題,您可以從 subscribe 方法中獲取密鑰。 請參閱以下對我有用的代碼。

注意:我創建了以下變量:

  1. productArray從我的 subscribe 方法構建結果。
  2. listData - 我的表的數據源(我在表中呈現了 firebase 調用)。
  3. displayColumnscolumnsTo Display - 這些是特定於我的表的。 您的實現會有所不同,因此您可以隨意忽略/修改與這些變量對話的代碼。

基本上,多注意下面的前 8 行:

this.productService.getProducts().subscribe(
  list => {
    this.productsArray = list.map(item => {
      return {
        $key: item.key,
        ...item.payload.val()
      };
    })
    this.listData = new MatTableDataSource(this.productsArray);
    this.displayedColumns = Object.values(Object.keys((this.productsArray)[0]))
    this.columnsToDisplay = this.displayedColumns.slice();
    this.columnsToDisplay.push("actions");
  }
);

最后,根據使用的 angular 版本,您可能希望通過更改customers: Customer[]; customers: Customer[] = [];

如果它解決了您的問題,請將此標記為已回答。 謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM