【问题标题】:Convert firebase.firestore.timestamp to date before patchValue of data in a reactive form以反应形式将 firebase.firestore.timestamp 转换为 patchValue 之前的日期
【发布时间】:2019-08-07 06:29:42
【问题描述】:

我正在尝试加载一个在 firestore 中存储为时间戳的字段,并填充一个使用日期格式的“mat-datepicker”表单控件。

有没有办法在“dob”数据到达 Angular Material 日期选择器控件之前修改它的格式?日期选择器不喜欢时间戳格式,并且出于明显的原因拒绝显示它。

下面是我尝试缩短现有代码减去任何转换尝试,因为我被卡住了!它甚至可能不起作用!完整的代码可以。

基本上使用传入的路径字符串来创建 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();
  }

}

【问题讨论】:

    标签: javascript angular firebase google-cloud-firestore


    【解决方案1】:

    我在 angularfirebase.slack.com 上提出了这个问题,并得到了这个解决方案。

          pipe(
            map(({dob, ...data}) => {
            return {
              ...data,
              dob: dob.toDate(),
            };
          }),
    

    点击(...

    在我的场景中,我在 Firestore 中有 5 个时间戳并且正在撞砖墙。上面的代码对我有用。

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 2011-05-05
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 2021-11-15
      相关资源
      最近更新 更多