javascript - 以 react 形式将 firebase.firestore.timestamp 转换为数据的 patchValue 之前的日期

标签 javascript angular firebase google-cloud-firestore

我正在尝试加载一个在 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/

相关文章:

javascript - 如何/为何从 <script> include 切换到 npm install?

javascript - 在多个 html 页面之间共享一个变量

javascript - Angular 4嵌套FormArrays无法读取null的属性 'push'

java - 当 Firebase 和 Android 中有新节点时,我的应用程序不断跳回 Activity

java - 无法在 firebase 数据库中保存消息

javascript - 使用自定义 View 对列范围 Highcharts 中的类别进行分组

javascript - 如何在运行时在 nestjs 中扫描所有装饰器值

angular - 为什么 AppComponent 默认没有 ngOnInit 函数?

angular - 错误 : (SystemJS) Can't resolve all parameters for ActivatedRoute: (? , ?, ?, ?, ?, ?, ?, ?)

node.js - 将 firepad 与 node.js 一起使用