Ionic 离子Angular :如何在www.example.com()中传递变量FormBuilder.group?

yacmzcpb  于 2023-09-28  发布在  Ionic
关注(0)|答案(1)|浏览(193)

是否有可能通过API将变量传递到formbuilder组中,以便将其包含在POST中到我的服务器?以下是我到目前为止所做的:

formAPICode: any;

  ngOnInit() {
this.ionicForm = this.formBuilder.group({
  apiKey: [this.formAPICode], // This is where the API Key should be appearing but doesnt. Console log returns NULL
  name: ['', [Validators.required, Validators.minLength(2)]],
  email: [
    '',
    [
      Validators.required,
      Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,3}$'),
    ],
  ],
  mobile: ['', [Validators.required, Validators.pattern('^[0-9]+$')]],
  street: ['', [Validators.required, Validators.minLength(2)]],
  unit: [],
  city: ['', [Validators.required, Validators.minLength(2)]],
  state: ['', [Validators.required, Validators.minLength(2)]],
  zip: ['', [Validators.required, Validators.minLength(5)]],
  summary: ['', [Validators.required, Validators.minLength(2)]],
  dateTime: [],
  existingCustomer: [],
  customerConsent: [Validators.required],
});

// Loads WP Company Data
this.wpService.postCompInfoDetails().subscribe((data) => {
  this.companyDetail = data;
  this.formAPICode = this.companyDetail.acf.forms_api_key;
  console.log(this.formAPICode); // returns 45678451-1124d-45ae-bf15-ABC
});

}
下面是控制台JSON

form data {"apiKey":null,"name":"John Doe","email":"[email protected]","mobile":"1324567894","street":"1234 Main St","unit":"Suite 202","city":"New York","state":"NY","zip":"10001","summary":"Description of summary","dateTime":null,"existingCustomer":null}

如果我把formAPICode改成这样,它就可以正常工作了。当我通过外部API引入API密钥时,它不会

formAPICode = '45678451-1124d-45ae-bf15-ABC';
1tu0hz3e

1tu0hz3e1#

看起来好像是在表单控件获得任何值之前,您将formAPICode值赋给了它。然后,当您实际从API获取值时,您正在更新formAPICode属性,但表单控件已经获得了初始值。
试试这个:

ngOnInit() {
this.ionicForm = this.formBuilder.group({
  apiKey: [], // You could leave this blank since we haven't gotten data from API. We will insert it later
  // ...your other inputs as normally...
});

// Loads WP Company Data
this.wpService.postCompInfoDetails().subscribe((data) => {
  this.companyDetail = data;
  this.formAPICode = this.companyDetail.acf.forms_api_key;

  // Now that we actually have the value from the API, we can patch that into the form like this
  this.ionicForm.patchValue({ apiKey: this.formAPICode });

  console.log(this.ionicForm.value) // Should print the entire form value with the actual apiKey that we got recently
});

相关问题