使用AngularFire2对象可观测的预填充形式
我无法使用AngularFire2使用存储在firebase中某个位置的数据预填充表单。该模板有多个输入,如:使用AngularFire2对象可观测的预填充形式,angular,typescript,angularfire2,Angular,Typescript,Angularfire2,我无法使用AngularFire2使用存储在firebase中某个位置的数据预填充表单。该模板有多个输入,如: <form (ngSubmit)="onSubmit(propertyForm.value)" #propertyForm="ngForm"> <div class="form-group"> <md-input-container> <input md-input placeholder="Postcode" type
<form (ngSubmit)="onSubmit(propertyForm.value)" #propertyForm="ngForm">
<div class="form-group">
<md-input-container>
<input md-input placeholder="Postcode" type="text" id="postcode" required [(ngModel)]="model.postcode" name="postcode">
</md-input-container>
</div>
</form>
然后连接到组件,该组件具有一个模型(属性),构造函数将该模型(属性)直接链接到我要在表单中显示的对象
export class PropertyFormComponent implements OnInit {
model: FirebaseObjectObservable<Property>;
submitted = false;
propertyForm;
constructor(private propertyService: PropertyService, af: AngularFire) {
this.model = af.database.object('/properties/MGQ34xmYDdT8IGLaj3zvBwZjWgW2');
}
}
导出类PropertyFormComponent实现OnInit{
模型:FirebaseObjectObservable;
提交=错误;
财产形式;
构造函数(私有属性服务:属性服务,af:AngularFire){
this.model=af.database.object('/properties/MGQ34xmYDdT8IGLaj3zvBwZjWgW2');
}
}
我知道对象路径是正确的,因为我可以提交表单并更新对象,但是ngModel绑定没有连接到Firebase对象,我不知道为什么。我尝试用手工制作的对象替换Firebase对象,效果很好。谢谢你的帮助 Firebase对象是一个可观察的
对象,而不是普通的JS对象,这意味着您不能按原样应用ngModel
。实际上,您可以尝试将可观察对象
转换为普通对象,这样就可以使用ngModel
因此,首先获取可观测数据,然后订阅:
constructor(private propertyService: PropertyService, af: AngularFire) {
this.model = af.database.object('/properties/MGQ34xmYDdT8IGLaj3zvBwZjWgW2');
this.model.subscribe(d => {this.model = d}); // add this line!
}
现在您有了一个普通对象可以使用:)
更好的选择是,如果您可以直接订阅对象,但不必使用Firebase,我不确定这是否有效,但您可以尝试:
af.database.object('/properties/MGQ34xmYDdT8IGLaj3zvBwZjWgW2')
.subscribe(d => {
this.model = d
})
感谢您的帮助,虽然表单仍然没有被填充,但似乎已经完成了操作,因为对象尚未定义。我认为这可能是一个时间问题,因为控制台日志显示此模型是正确的,但在所有错误之后出现。欢迎!至于未定义的错误:这是异步的,所以在检索数据之前呈现视图,您可以使用*ngIf*
来解决它,所以您可以使用
来实现这个技巧:)太好了,这应该足够让我从这里解决它。谢谢