Angular 离子角模型误差参考接口中的子对象

Angular 离子角模型误差参考接口中的子对象,angular,typescript,firebase,ionic-framework,ionic3,Angular,Typescript,Firebase,Ionic Framework,Ionic3,这是我的界面: 预订界面 export interface Booking { "dateBooking": Date; "period": { "morning": boolean; "afternoon": boolean; "night": boolean; } } addbooking.ts ... import { Booking } from '../../models/booking/booking.interface'; ... export

这是我的界面:

预订界面

export interface Booking {
  "dateBooking": Date;
  "period": {
    "morning": boolean;
    "afternoon": boolean;
    "night": boolean;
  }
}
addbooking.ts

...
import { Booking } from '../../models/booking/booking.interface';
...
export class AddbookingPage {

  //declare a property of interface type
  public booking = {} as Booking;

   constructor() {
  }
...
当我尝试在视图中引用booking.period.morning或我的对象时段的任何子属性时,Ionic会引发错误:

addbooking.html

  <ion-item>
    <ion-label>Morning</ion-label>
    <ion-checkbox [(ngModel)]="booking.period.morning"></ion-checkbox> 
  </ion-item>
我试图实现一个复选框并将数据保存在Firebase中。如果有任何其他方法可以实现这一点,我接受建议。

您需要:

初始化对象以匹配接口

public booking: Booking = {
  dateBooking: new Date(),
  period: {
   morning: true,
   afternoon: false,
   night: false, 
  }  
}
或者隐藏复选框,直到对象具有
period.morning
属性

<ion-item>
  <ion-label>Morning</ion-label>
  <ion-checkbox *ngIf="booking && booking.period && typeof booking.period.morning === 'boolean'" [(ngModel)]="booking.period.morning"></ion-checkbox> 
</ion-item>

早晨

使用类而不是接口
公共预订
是一个空对象,
as booking
只告诉Typescript,它应该拦截
{}
as
booking
type。如果您稍后要初始化,可以在html中使用安全导航操作符。它解决了我的问题。我不知道是否需要初始化对象。很高兴我能帮上忙。你能投票接受我的回答吗?:)我试过了,但是:~谢谢你的反馈!声誉低于15的人所投的票将被记录,但不会改变公开显示的post分数
<ion-item>
  <ion-label>Morning</ion-label>
  <ion-checkbox *ngIf="booking && booking.period && typeof booking.period.morning === 'boolean'" [(ngModel)]="booking.period.morning"></ion-checkbox> 
</ion-item>