我正在尝试加载一个在 firestore 中存储为时间戳的字段,并填充一个使用日期格式的“mat-datepicker”表单控件。
有没有办法在“dob”数据到达 Angular Material datepicker 控件之前修改它的格式?日期选择器不喜欢时间戳格式,并且出于显而易见的原因拒绝显示它。
下面是我尝试缩短现有代码减去任何转换尝试,因为我被卡住了!它甚至可能不起作用!不过完整代码确实如此。
基本上使用传入的路径字符串创建 Firestore 文档的实例,然后将值修补到 myForm 控件中。
我知道 firebase.firestore.Timestamp 有一个 toDate() 选项,但我是一个 Angular 菜鸟,需要一些关于如何在将值存储在控件中之前将时间戳转换为日期的指示?
// Firestore Document
private fireDoc: AngularFirestoreDocument;
@Input() path: string;
myForm: FormGroup;
constructor(private fb: FormBuilder, private afs: AngularFirestore) { }
ngOnInit() {
this.myForm = this.fb.group({
firstName: new FormControl(''),
middleName: new FormControl(''),
lastName: new FormControl(''),
dob: new FormControl(),
});
this.loadDoc();
}
loadDoc() {
this.fireDoc = this.afs.doc(this.path);
this.fireDoc
.valueChanges()
.pipe(
tap(doc => {
if (doc) {
this.myForm.patchValue(doc);
}
}),
take(1)
)
.subscribe();
}
}
最佳答案
我在 angularfirebase.slack.com 上问了这个问题,并得到了这个解决方案。
pipe(
map(({dob, ...data}) => {
return {
...data,
dob: dob.toDate(),
};
}),
点击(...
在我的场景中,我在 Firestore 中有 5 个时间戳并且正在撞墙。上面的代码对我有用。
关于javascript - 以 react 形式将 firebase.firestore.timestamp 转换为数据的 patchValue 之前的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55195093/