import { Component, OnInit } from '@angular/core';
import { CategoryService } from 'src/app/service/category.service';
@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();
console.log(this.categories$);
}
ngOnInit(): void { }
}
@Injectable({
providedIn: 'root'
})
export class CategoryService {
constructor(private db: AngularFireDatabase) { }
getCategories() {
return this.db.list('/categories')
}
}
<div class="form-group">
<label for="category">Category</label>
<select id="category" class="form-control">
<option value=""></option>
<option *ngFor="let c of (categories$|async)" [value]=""> {{c.name}} </option>
</select>
</div>
尝试如图所示从Firebase实时数据库中检索对象,并得到如图2所示的错误。如何解决该问题?请帮忙。
答案 0 :(得分:0)
首先,您需要使用valueChange():
export class ProductFormComponent implements OnInit {
categories$;
constructor(categoryService: CategoryService) {
this.categories$ = categoryService.getCategories().valueChanges();
// console.log(this.categories$);
}
ngOnInit(): void { }
}
<div class="form-group">
<label for="category">Category</label>
<select id="category" class="form-control">
<option value=""></option>
<option *ngFor="let c of categories$|async" [value]=""> {{c.name}} </option>
</select>
</div>
答案 1 :(得分:0)
constructor(categoryService:CategoryService, private productService:ProductService) {
this.categories$ = categoryService.getCategories().snapshotChanges();
}
<option class="form-control" *ngFor="let c of (categories$|async)" [value]="c.key"> {{c.payload.val().name}} </option>
getCategories() {
return this.db.list('/categories', ref => (ref.orderByChild('name')));
}
这给了我正确的结果。 感谢您的帮助。
答案 2 :(得分:0)
在您的服务中使用this.db.list('/categories').snapshotChanges();
。
export class CategoryService {
constructor(private db: AngularFireDatabase) {}
getCategories(){
return this.db.list('/categories').snapshotChanges();
}
}
export class ProductFormComponent implements OnInit {
categories$: Observable<SnapshotAction<unknown>[]>;
constructor(categoryService: CategoryService) {
this.categories$ = categoryService.getCategories();
}
ngOnInit(): void {
}
}
也在ProductFormComponent.html中
<div class="form-group">
<label for="category">Category</label>
<select id="category" class="form-control">
<option value=""></option>
<option *ngFor="let c of categories$ | async" [value]="c.key">
{{ c.payload.val()["name"] }}
</option>
</select>
</div>