在文本框数据加载上获得未定义的错误(Angular 2)

时间:2017-04-23 03:20:13

标签: angular angular2-forms angular2-services

我正在尝试预先填充文本框。我正在使用web api调用它,我的服务调用工作正常,但当我尝试加载文本框上的数据时,我收到了以下错误。

customer.component.html: caused by: Cannot read 
property 'firstName' of undefined
Error: Error in app/customers/customer.component.html:18:31 caused by: 
Cannot read property 'firstName' of undefined

页面加载完成后,我在按钮点击时检查了customer.firstName值,但它显示的值正确。不知道为什么我在初始页面加载时出错。

customer.component.html

<input id="firstNameId" type="text" [(ngModel)] = customer.firstName 
  name="firstName" #firstNameVar="ngModel" />

CustomerComponent

export class CustomerComponent implements OnInit {
   customer: ICustomer;
   errorMessage: string;
   constructor(private _route:ActivatedRoute, 
            private customerService :CustomerService){
   }
   ngOnInit(): void {
     this._route.params.subscribe(
        pa => {
            this.getPerson();
      });
    }
   getPerson() {
    this.customerService.getCustomer()
    .subscribe(
            (cust:ICustomer) =>
            {
                this.customer = cust;
            },
        (error: any) => this.errorMessage = <any>error
    )
   }
 }

客户界面

 export interface ICustomer {
    firstName:string,
    lastName:string,
    email:string
 }

2 个答案:

答案 0 :(得分:1)

使用安全运算符检查值是否存在 customer?.firstName

<input id="firstNameId" type="text" [(ngModel)] = customer?.firstName 
  name="firstName" #firstNameVar="ngModel" />

答案 1 :(得分:1)

您只需定义客户对象,而应使用以下所需属性初始化对象:

customer: ICustomer = {
  firstName: null
};

Demo with explicit assignment

或者您可以使用类而不是接口为客户定义模型并初始化属性,如下所示:

export class App implements OnInit {
  customer:Customer;
  constructor() {
    this.customer = new Customer('Anil','Nani','anil@nani.com')
  }

  ngOnInit() {}
}

Demo with class