Angular /如何确保不完整的服务器模型不会破坏ngModel?

时间:2017-06-28 16:09:36

标签: angular

以下控件的值绑定到employee对象。如果服务器不会返回员工,我怎样才能确保这不会中断?

 <input type="text" class="form-control" name="employee-name" [(ngModel)]="employee.person.details.name" required>

有没有办法在运行中创建丢失的对象路径?

2 个答案:

答案 0 :(得分:0)

您可以为员工创建一个模型类,并使用空白人员详细信息名称启动它,然后使用该模型类实例化您的员工属性

export class YourClass {

  employee: Employee = new Employee(); //default constructor
  ...
  service.getEmployee().subscribe((res) => this.employee = new Employee(res)); //custom constructor
  ...

}

答案 1 :(得分:0)

返回并实际查看我的代码:-) ...我看到我有一个初始化方法,为此目的返回一个初始化对象:

initializeProduct(): IProduct {
    // Return an initialized object
    return {
        id: 0,
        productName: null,
        productCode: null,
        category: null,
        tags: [],
        releaseDate: null,
        price: null,
        description: null,
        starRating: null,
        imageUrl: null
    };
}

你需要更复杂,因为它有更多级别的子对象。但你可以做类似的事情。我在创建一个&#34; new&#34;进入以确保我没有看到&#34; undefined&#34;错误。