【问题标题】:Angular 2: populate FormBuilder with data from httpAngular 2:使用来自 http 的数据填充 FormBuilder
【发布时间】:2017-01-05 08:20:39
【问题描述】:

我在组件中使用 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 获取数据,因此 customer 为空。但是如何解决呢?

更新:我的 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);
  }

}

【问题讨论】:

  • 只需添加一个默认值作为一个空字符串,它将显示给等待 http 结果的用户...customer=defaultCustomer={name:''}

标签: javascript http angular rxjs


【解决方案1】:

正如@Bhushan Gadekar 所说,您正在访问尚未初始化的客户。

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

使用设置器:

@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 名称。

重点:

你不应该访问来自构造函数的输入,因为它们还没有填充,所有输入都应该在 ngOnInit 钩子之前填充(至少是同步的)。看看Lifecycle hooks documentation

【讨论】:

  • 如果我有 20 个字段,那么设置每个 val(((
  • 只是循环遍历属性,这不是问题
  • 无论如何,这是唯一的方法。
  • 另外:map 将不起作用:this.customer.map is not a function
  • customer 必须是 ObservableICustomer,而不是 ICustomer,如果您想使用 map() 方法。
【解决方案2】:

我可以看到您正在尝试访问未填充的 customer 对象。

这里的问题是 http 调用需要一些时间才能解决。因此,即使未定义,您的视图也会尝试访问客户对象。

试试这个:

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

虽然您访问name 属性的方式也不好。 最好的方法是创建一个客户模型并将您的属性用作className.propertyName

这有帮助。

【讨论】:

  • export interface ICustomer { name: string; address: string; } 我有客户模型...
  • 你可以直接访问name属性,上面的方法有效吗? @brabertaser19
  • ngOnInit() { console.log(this.customer); - 对象 {}(空)但在视图中:/{{customer.name}}/ - 输出正常名称...奇怪的东西(输入中和以前一样:空 val)
【解决方案3】:

用 ngAfterViewInit 代替 ngOnInit

【讨论】:

  • 我告诉过你)这不起作用:因为 formBuilder 应该在初始化时初始化,否则我会得到:formGroup expects a FormGroup instance. Please pass one in.
【解决方案4】:

不要在 component.ts 中使用 subscribe 并在 component.html 中添加异步管道,如下所示: &lt;customer-form [customer]="customer | async"&gt;&lt;/customer-form&gt;

【讨论】:

  • do not use subscribe 是什么意思? (也检查我的更新)
  • plunkr 为例。
  • 请尝试在plunkr中设置您的代码的简单版本。
  • 不是您的代码的完整副本,只是一个简单的版本。有空时与 plunkr 一起玩。这并不难。它将帮助人们更轻松地理解您的问题。
猜你喜欢
  • 2018-03-31
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
  • 2020-08-07
  • 2023-04-09
  • 1970-01-01
  • 2015-11-09
  • 2019-05-19
相关资源
最近更新 更多