我试图从firebase检索单个对象并输出到表单进行编辑。我用下面的方法检索单个对象:
this.product = this.af.database.object('/products/'+ productId);
并尝试将其输出到模板中,如下所示:
<ion-item>
<ion-label stacked>Date</ion-label>
<ion-datetime [(ngModel)]="product.date" name="date" required></ion-datetime>
</ion-item>
<ion-item>
<ion-label stacked>Content</ion-label>
<ion-input type="text" [(ngModel)]="product.content" name="content" required></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>Amount</ion-label>
<ion-input type="number" [(ngModel)]="product.amount" name="amount"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>Category</ion-label>
<ion-select type="text" [(ngModel)]="product.category" name="category" required>
<ion-option>Book</ion-option>
<ion-option>Baby</ion-option>
<ion-option>Clothing</ion-option>
</ion-select>
</ion-item>
</ion-list>
但是输出到表单的字段不起作用。请帮忙。我试过像这样应用异步运算符
<ion-input type="number" [(ngModel)]="product.amount" name="amount" value="product.amount | async"></ion-input>
但它也不起作用。
您必须实现subscribe pattern
,如下所示。
service.ts
product : FirebaseObjectObservable<data-type>;
constructor(public af: AngularFire) {}
//get product
getProduct(productId : string): FirebaseObjectObservable<data-type> {
return this.product = this.af.database.object('/products/'+ productId);
}
page.ts
public product: data-type;
constructor(public service: Service) {
this.service.getProduct(productId).subscribe(snap => {
this.product = snap;
});
}
你可以使用当前的angularfire2版本,如下所示
controller.ts
import { Observable } from 'rxjs/Observable';
.......
product : Observable<any>;
constructor(public db: AngularFireDatabase) {
this.product = this.db.object('/products/'+ productId)
.snapshotChanges().map(res => {
return res.payload.val();
});
}
HTML
<ion-input type="number" value="{{(product|async)?.amount}}" [(ngModel)]="product.amount" name="amount"></ion-input>