无法从 Angular5 模板中的火力基地获取$key



我在后端使用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 的值。类别的值尚未定义。

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

请指导我我错过了什么。

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

类别.服务.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>

最新更新