javascript – Angular 2:使用http中的数据填充FormBuilder

我从组件中使用rjsx从http获取我的数据(让我们将其命名为customer).

然后我在客户中使用内部组件:

<customer>
  <customer-form [customer]="customer"></customer-form>
</customer>



<!-- [customer]="customer" // here is data from http -->

在客户形式我有:

@Input() customer:ICustomer;

complexForm : FormGroup;



constructor(fb: FormBuilder) {

  this.complexForm = fb.group({
    'name': [this.customer['name'], Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(255)])]
  });
}

但我得到:

Cannot read property 'name' of undefined
TypeError: Cannot read property 'name' of undefined

如果我理解正确:这是因为构造函数被调用,但数据尚未从http获取,因此客户是空的.但是如何解决这个问题?

upd:我的http数据得到:

   getCustomer(id) {
    this.customerService.getCustomer(id)
      .subscribe(
        customer => this.customer = customer,
        error =>  this.errorMessage = <any>error);
  }
  ----


@Injectable()
export class CustomerService {

  private customersUrl = 'api/customer';

  constructor (private http: Http) {}

  getCustomers (): Observable<ICustomer[]> {
    return this.http.get(this.customersUrl)
      .map(this.extractData)
      .catch(this.handleError);
  }

  getCustomer (id): Observable<ICustomer> {
    return this.http.get(this.customersUrl + '/' + id)
      .map(this.extractData)
      .catch(this.handleError);
  }



  private extractData(res: Response) {
    let body = res.json();
    return body || { };
  }


  private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

}
最佳答案
正如@Bhushan Gadekar所说,当您尚未初始化客户时,您正在访问该客户.

有多种方法可以正确处理:

使用setter:

@Input("customer") 
set _customer(c:ICustomer){
  this.customer=c;
  this.complexForm.get("name").setValue(c.name,{onlySelf:true});
}
customer:ICustomer;
complexForm : FormGroup;

constructor(fb: FormBuilder) {

  this.complexForm = fb.group({
    'name': [null, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(255)])]
  });
}

使用Observable

在这里,客户需要成为ICustomer的Observable

@Input() customer:Observable<ICustomer>;

complexForm : FormGroup;

constructor(fb: FormBuilder) {
  this.complexForm = fb.group({
    'name': [this.customer['name'], Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(255)])]
  });
}

ngOnInit(){
  this.customer.map(c=>this.complexForm.get("name").setValue(c.name,{onlySelf:true}))
  .subscribe();
}

混合两者:

@Input("customer") 
set _customer(c:ICustomer){
  this.customer.next(c);
}
customer=New Subject<ICustomer>();
complexForm : FormGroup;

constructor(fb: FormBuilder) {
  this.complexForm = fb.group({
    'name': [null, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(255)])]
  });
}

ngOnInit(){
  this.customer.map(c=>this.complexForm.get("name").setValue(c.name,{onlySelf:true}))
  .subscribe();
}

多个属性的案例:

如果您不想逐个编写每个表单更新,并且如果表单的字段名称与您的对象相同,则可以遍历客户属性:

Object.keys(customer).forEach(k=>{
  let control = this.complexForm.get(k);
  if(control)
    control.setValue(customer[k],{onlySelf:true});
});

请注意,仅当表单的控件的命名方式与客户的属性相同时,此代码才有效.如果没有,您可能需要将客户属性名称的哈希映射到formControls名称.

很重要的一点:

Yous永远不应该从构造函数访问输入,因为它们尚未填充,所有输入应该在ngOnInit挂钩之前填充(至少是同步的).看看Lifecycle hooks documentation

转载注明原文:javascript – Angular 2:使用http中的数据填充FormBuilder - 代码日志