typescript 如何解决ngOnInit Async Angular问题?

xdnvmnnf  于 2023-03-31  发布在  TypeScript
关注(0)|答案(2)|浏览(143)

我需要initializeForm函数总是在合约列表设置后被调用,通常在react中我只会使用带有合约回调的UseEffect重新渲染组件,我如何确保initializeForm()在合约设置一致后被调用?现在它有时工作,有时不工作。

ngOnInit() {
    this.service.appContext = this.appContext;
    this.teamQueueService.GetContracts().subscribe(res => {
      this.contracts = res.userContractList;
      this.initializeForm();
    });
  }

  // Filter Validations
  get advanceSearchForm() {
    return this.searchForm.controls;
  }

  //#region Validation Functions
  initializeForm(): void {
    this.searchForm = this.fb.group({
      facilityName: ['', [Validators.maxLength(300), Validators.minLength(1)]],
      address: ['', [Validators.maxLength(300), Validators.minLength(1)]],
      city: ['', [Validators.maxLength(300), Validators.minLength(1), Validators.pattern('^[a-zA-Z ]*$')]],
      state: '',
      zipCode: ['', [Validators.maxLength(10), Validators.minLength(5)]],
      // tslint:disable-next-line:quotemark
      ccn: ['', [Validators.maxLength(6), Validators.minLength(6), Validators.pattern("^[a-zA-Z0-9 '-]+$")]],
      npi: ['', [Validators.maxLength(10), Validators.minLength(10), Validators.pattern('[0-9]\\d{9}')]],
      location: [5],
      distance: [0],
      disabled: true,
      contracted: false,
      participating: false,
      contract: this.contracts.find(c => c.contractId === this.facilityVerificationInfo.contractId).contractId,
      selectedContract: this.contracts.find(c => c.contractId === this.facilityVerificationInfo.contractId).contractId,
      careSetting: 0
    });
  }
p4rjhz4m

p4rjhz4m1#

你的getter应该返回一个可选的/nullable:

get advanceSearchForm(): MyForm | undefined {
    return this.searchForm?.controls;
}

这取决于你在模板中处理undefined。

ua4mk5z4

ua4mk5z42#

设法通过将函数调用存储在ngOnChanges中来修复此问题,该ngOnChanges查找facilityVerificationInfo是否存在。

ngOnInit() {
    this.initializeForm();
    this.service.appContext = this.appContext;
    this.teamQueueService.GetContracts().subscribe(res => {
      this.contracts = res.userContractList;
      // this.updateDefaultSelect();
    });
  }

  // Filter Validations
  get advanceSearchForm() {
    return this.searchForm.controls;
  }
  //set default contract and stuff
  updateDefaultSelect() {
    this.searchForm.controls['contract'].setValue(this.facilityVerificationInfo.contractId);
    this.searchForm.controls['selectedContract'].setValue(this.facilityVerificationInfo.contractId);
    const data = {
      source: 'default',
      value: this.facilityVerificationInfo.contractId
    };
    this.onContractChange(data);
  }

  // watches for facilityVerificationInfo Update
  ngOnChanges(changes: SimpleChanges): void {
    if (this.facilityVerificationInfo) {
      this.updateDefaultSelect();
    }
  }

相关问题