【问题标题】:How to get a key of node in Angularfirelist<unknown> from Firebase Realtime Database如何从 Firebase 实时数据库中获取 Angularfirelist<unknown> 中的节点键
【发布时间】:2020-07-27 23:58:18
【问题描述】:

我正在从 Firebase 数据库中获取这些类别。

数据库快照:

这里是CategoryServicegetCategories 正在返回AngularFireList&lt;unknown&gt;

export class CategoryService {
  constructor(private db: AngularFireDatabase) {}

   getCategories(){
     return this.db.list('/categories', category => category.orderByChild('name'));
   }
}

这是ProductComponant

export class ProductFormComponent {
  categories;
  constructor(
    categoryService: CategoryService,
    private productService: ProductService
  ) {
    categoryService.getCategories().valueChanges().subscribe((categories) => {
      this.categories = categories;
    });
  }

categories 我得到了这个。

这是 HTML 标记

<div class="form-group">
        <label for="category">Category</label>
        <select ngModel name="category" class="form-control" id="category">
            <option *ngFor="let c of categories" [value]="c.$key"> {{c.name}} </option>      
        </select>
    </div>

这里我想获取Categories中每个节点的key/id,并在DropDown这个category中设置为Value。

我试过c.keyc.$keyc.idc | json。但没有一个有效。

【问题讨论】:

  • 你能在这里介绍一下你在类别中得到了什么吗?
  • @Sunny Parekh:问题已更新。

标签: angular typescript firebase-realtime-database angularfire2


【解决方案1】:

好的,我明白了。问题在于.valueChanges(),因为它只返回数据而不返回元数据。所以我把我的代码改成了。

CategoryService.ts:

export class CategoryService {
  aflCategories: AngularFireList<any>;
  constructor(private db: AngularFireDatabase) {}

   getCategories(){
     this.aflCategories = this.db.list('/categories', category => category.orderByChild('name'));
     return this.aflCategories
     .snapshotChanges()
     .pipe(map(changes => changes
     .map(c => ({ key: c.payload.key, ...c.payload.val() }))));
   }
}

ProductFormComponent.ts:

export class ProductFormComponent {

  categories$: Observable<any[]>;

  constructor(
    categoryService: CategoryService,
    private productService: ProductService,
    private db: AngularFireDatabase
  ) {
    this.categories$ = categoryService.getCategories();
  }

ProductFormComponent.html

<option *ngFor="let c of (categories$ | async)" [value]="c.key"> {{c.name}} </option>

现在我也拿到了“钥匙”。

【讨论】:

    【解决方案2】:

    嘿,请改成如下图:

    <div class="form-group">
            <label for="category">Category</label>
            <select name="category" class="form-control" id="category" [(ngModel)}="category">
                <option *ngFor="let c of categories" [ngValue]="c.name"> {{c.name}} </option>      
            </select>
        </div>
    

    您的控制器文件中应该有一个名为 category 的属性。进行此更改后,在选择项上,您可以在类别变量中看到所选值。

    【讨论】:

    • c.name 正在返回“名称”的值,但我想要节点的“键”。就像在“调味料”节点中一样,我想要“调味料”,而不是“调味料和香料”。
    猜你喜欢
    • 2018-07-28
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多