【问题标题】:Unable to fetch $key from firebase in Angular5 template无法从 Angular5 模板中的 firebase 获取 $key
【发布时间】:2018-10-22 19:15:03
【问题描述】:

我在后端使用 firebaseAngular5 中制作表单。该表单包含几个输入字段和一个下拉菜单。

我能够在下拉选项中填充值 ({{ c.name }}),但选项的值属性为空,我正在尝试使用 c.$key 填充。

下面是 HTML 部分:

<form #f="ngForm" (ngSubmit)="save(f.value)">
    <!-- other input fields here -->
    <div class="form-group">
        <label for="category">Category</label>
        <select ngModel name="category" id="category" class="form-control">
          <option value=""></option>
          <option *ngFor="let c of categories$ | async" [value]="c.$key"> 
            {{ c.name }} 
          </option>
        </select>
    </div>
</form>

这是我的组件:

import { CategoryService } from './../../category.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-product-form',
  templateUrl: './product-form.component.html',
  styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {
  categories$;

  constructor(categoryService: CategoryService) {
    this.categories$ = categoryService.getCategories();
  }

  ngOnInit() {
  }

  save(product) {
    console.log(product);
  }

}

服务:

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

    @Injectable()
    export class CategoryService {

      constructor(private db: AngularFireDatabase) { }

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

我正在控制台上打印表单 json 的值。 category 的值未定义。

{title: "Title", price: 10, category: "undefined", imageUrl: "xyz"}

请指导我缺少什么。

【问题讨论】:

  • @R.Richards 谢谢。这很有帮助。我使用 c.key 获取密钥并在服务方法中做了以下更改:`getCategories() { return this.db.list('/categories', ref => ref.orderByChild('name') ) .snapshotChanges().map(categories => { return categories.map(c => ({ key: c.payload.key, ...c.payload.val() })); }); }`
  • 我也这样做。似乎可以很好地满足需要。很高兴您发现该链接有帮助。我想我第一次遇到这个问题时使用了相同的答案。

标签: angular firebase firebase-realtime-database angular5


【解决方案1】:

$key 已被弃用。请改用snapshotChanges()

category.service.ts

getCategories() {
    return this.db
        .list('/categories', (ref) => ref.orderByChild('name'))
        .snapshotChanges()
        .pipe(
        map((actions) => {
            return actions.map((action) => ({
                key: action.key,
                val: action.payload.val(),
            }));
        }));

}

app.component.html

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-16
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2019-07-08
    • 1970-01-01
    相关资源
    最近更新 更多