【发布时间】:2018-10-22 19:15:03
【问题描述】:
我在后端使用 firebase 在 Angular5 中制作表单。该表单包含几个输入字段和一个下拉菜单。
我能够在下拉选项中填充值 ({{ 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