---- ---- product.service.ts
export class ProductService {
productRef: AngularFireObject<any>;
product: Observable<any>;
constructor( private db: AngularFireDatabase ) { }
getOne( productId ) {
this.productRef = this.db.object('/products' + productId);
return this.product = this.productRef.snapshotChanges();
}
}
--- product.component.ts ---
export class ProductFormComponent implements OnInit {
categories$;
product: any;
constructor(
private router: Router,
private route: ActivatedRoute,
private categoriesService: CategoryService,
private productService: ProductService
) { }
ngOnInit() {
this.categories$ = this.categoriesService.getCategories();
const id = this.route.snapshot.paramMap.get('id');
if ( id ) {
this.productService.getOne( id ).take( 1 ).subscribe(
p => this.product = p
);
}
}
}
--- product.component.html ---
<form #f="ngForm" (ngSubmit)="save(f.value)" class="products">
<div class="form-group"><label for="title">Title</label>
<input #title="ngModel" [(ngModel)]="product.???.title" name="title" type="text" class="form-control">
</div>
<button class="btn btn-primary">Save</button>
</form>
--- json格式数据库---
{ "payload": { "category": "africa", "imageUrl": "image 01", "price": 12, "title": "test04" }, "type": "value", "prevKey": null, "key": "-KzWO7MPXevJSgLEdKoT" }
---问题--- 如何显示firebase数据库中给定id的数据。
答案 0 :(得分:0)
您可以像以下一样使用它:
[(ngModel)]="product.payload.title"
但需要将其包裹为b / w *ngIf='product.payload'
喜欢:
<div class="form-group" *ngIf='product?.payload'>
<label for="title">Title</label>
<input #title="ngModel" [(ngModel)]="product.payload.title" name="title" type="text" class="form-control">
</div>
注意:您不能使用安全操作员?与2路数据绑定,所以 在约束时需要重视客观性
答案 1 :(得分:0)
您可以循环访问有效负载并获取数据
声明变量product:any = {};
if ( id ) {
this.product.name = "loading...";
this.productService.getOne( id ).take( 1 ).subscribe(
p => {
p.payload.forEach(product => {
this.product = product;
}
}
);
并在你的HTML中
<input #title="ngModel" [(ngModel)]="product.title" name="title" type="text" class="form-control">
您正在获取数据异步,因此需要一些时间this.product.name = "loading...";
这样可以防止出现空值错误。
或者您可以从product.service.ts
getOne( productId ) {
this.productRef = this.db.object('/products' + productId);
return this.product = this.productRef.snapshotChanges().subscribe(action
=> {
return { key: action.payload.key, ...action.payload.val() }
});
}
现在你可以像这样使用
if ( id ) {
this.product.name = "loading...";
this.productService.getOne( id ).take( 1 ).subscribe(
p => this.product = p
);