Angular中ngForm下拉框值返回undefined问题求助
Hey there, let's break down why your category select is returning undefined and how to fix it:
The Root Cause
Looking at your CategoryService, you're using valueChanges() to fetch categories from Firebase:
getCategories(){ return this.db.list('/categories').valueChanges() }
The valueChanges() method only returns the raw data of your Firebase records, not metadata like the record's $key. So when you try to bind [value]="c.$key" in your template, c.$key doesn't exist—it's undefined, which gets passed as the select's value.
Solution 1: Use snapshotChanges() to Include the Key
Modify your CategoryService to use snapshotChanges() instead, which gives you access to each record's key. We'll map the snapshot data to include the key as a property:
import { Injectable } from '@angular/core'; import { AngularFireDatabase } from '@angular/fire/database'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class CategoryService { constructor(private db: AngularFireDatabase) { } getCategories(){ return this.db.list('/categories').snapshotChanges().pipe( map(changes => changes.map(c => ({ key: c.payload.key, ...c.payload.val() })) ) ); } }
Then update your template to use the new key property we added:
<option *ngFor="let c of categories$ | async" [value]="c.key"> {{ c.name }} </option>
Solution 2: Bind to the Category Name (If You Don't Need the Key)
If you don't actually need the Firebase key and just want to pass the category name as the value, simplify your template to bind directly to c.name:
<option *ngFor="let c of categories$ | async" [value]="c.name"> {{ c.name }} </option>
This will make the category field return the selected name instead of undefined.
Verify the Fix
After making either change, submit the form again. Your console output should now show a valid value for category (either the Firebase key or the category name, depending on which solution you chose).
内容的提问来源于stack exchange,提问作者Deepak

