【问题标题】:matDatePicker with angular cloud firestore and [(ngModel)]matDatePicker 带有角度云火库和 [(ngModel)]
【发布时间】:2018-11-25 12:30:01
【问题描述】:

在实时数据库中,我使用了角度材料 matDatePicker 来保存日期新闻。

由于我继续使用 firestore 集合,当我在 Angular 服务中调用保存的日期时,它会将其显示为一个对象

  "date": {
     "seconds": 1529445600,
     "nanoseconds": 0
  },

我不能将它与 [(ngModel)] 一起使用。看起来它不再是一个字符串,所以 matDatepicker matInput 不再识别它了。

那么我应该如何将 matDatepicker 值绑定到我的视图的 ngModel 中?

模板:

    <mat-form-field>
      <input matInput [matDatepicker]="picker" 
        placeholder="Date" required readonly
        [(ngModel)]="news.date"
            (ngModelChange)="updateField(news,'date',news.date)">
      <mat-datepicker-toggle matSuffix type="button" [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
    </mat-form-field>

服务:

getNewsWithKey(key: string): Observable<SingleNews> {
const newsPath = `news/${key}`;
this.news = this.afs.doc<any>(newsPath)
  .snapshotChanges().map(action => {
    const $key = action.payload.id;
    const data = { $key, ...action.payload.data() }
    return data;
  });
return this.news}

【问题讨论】:

    标签: angular datepicker angular-material ngmodel angularfire5


    【解决方案1】:

    正在保存的对象的类型似乎是firebase.firestore.Timestamp。此更改是在 Firebase JS SDK v4.13.0 中添加的,其中 JavaScript Date 对象将被保存为 Timestamp 类型。

    Timestamp 类中,有一个名为toDate 的方法,它将Timestamp 转换为JavaScript 的Date 对象。

    您可以这样做:

    • 您可以尝试使用转换后的Timestamp 以及远程保存的任何数据分配一个临时对象。

      getNewsWithKey(key: string): Observable<SingleNews> {
        const newsPath = `news/${key}`;
        this.news = this.afs.doc<any>(newsPath)
          .snapshotChanges().map(action => {
            const $key = action.payload.id;
            const data = Object.assign(action.payload.data(), { date: action.payload.data().date.toDate(), $key: action.payload.id });
            return data;
          });
        return this.news;
      }
      

    【讨论】:

      猜你喜欢
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-24
      • 1970-01-01
      • 2017-12-06
      相关资源
      最近更新 更多