如何从 API 请求向 Angular 中的 formControl 设置值?

问题描述 投票:0回答:1

我有一个从 REST API 获取数据的服务。返回结果如下所示:

{
 "users": [
  {
    "id": 1,
    "firstname": "John",
    "email": "[email protected]",
    "lastname": "Smith"
  }
 ]
}

我希望能够获取电子邮件值并将其默认设置为我的 emailID formControl:

templateForm = this.fb.group({
  appCode: [''],
  accountType: [''],
  emailId: [''],
  IDV: [''],
  emailSubject: [null,Validators.required],
  emailBlurb: [null,Validators.required],
  envelopeRequest: this.fb.group({
   compositeTemplates: this.fb.array([this.newCompositeTemplate()]),
  }),
});

我已在 ngOnInit 内部添加了服务以及 patchValue 方法,但表单控件未填充。

ngOnInit() {
 this.userservice.getUsers().subscribe((res:User) => {
  this.userData =res;
 }); 
 this.templateForm;    
 this.templateForm.patchValue({
  emailId: this.userData.email    
 });
}

我不确定为什么会发生这种情况,如果我在 patchValue 中硬编码一个电子邮件地址,它就可以正常工作。感谢您对此的任何回应。我添加了一个链接以供参考。 堆栈闪电战

angular angular-reactive-forms patchvalue
1个回答
0
投票

我会这样做,因为您请求返回用户而不是简单的

User
数据。

ngOnInit() {

    this.userservice.getUsers().subscribe((res:any) => {
 
    this.userData =res.users[ 0 ];
 
    this.templateForm.patchValue({
      emailId: this.userData.email   
    });

  }); 
}

工作 Stacklbitz

© www.soinside.com 2019 - 2024. All rights reserved.