【问题标题】:Problem when using observable object in FormGroup在 FormGroup 中使用可观察对象时出现问题
【发布时间】:2020-01-04 13:55:33
【问题描述】:

我遇到了一个无法解决的问题。我有一个函数可以创建我的 FormGroup 并创建表单字段和验证器。验证器是自定义验证器,需要来自可观察对象的值,这就是我的问题开始的地方。

目前我在构造函数部分调用创建 FormGroup 的函数,然后在 onNgInit 中创建订阅我的 observable。这样做我的代码抱怨我从可观察到的数据是未知的。那是因为表单函数引用了没有被调用的东西。如果我将表单函数移动到我的可观察代码之后,我会收到错误,我需要有一个 FormGroup。

那么,确保表单代码可以运行并可以访问 observable 返回的对象的最佳方法是什么?还是最好先创建一个包含空数据的对象,以便表单可以找到值,然后让订阅更新它?

paswdProfile$: Observable<IPasswordProfile>
paswdProfile: IPasswordProfile

constructor(@Inject(MAT_DIALOG_DATA) public data: any, private dialogRef: MatDialogRef<PasswordComponent>,
        private adminService: AdminService, private route: ActivatedRoute, private cbLookupService: CouchbaseLookupService,
        private router: Router, private dialog: MatDialog, private toasterService: ToasterService, private fb: FormBuilder) {

    this.passwordForm = this.createPasswordForm()
}



ngOnInit() {
    this.paswdProfile$ = this.adminService.getPasswordProfile("8084ea42-633e-4c28-bc7a-372aa58a4d1c")
    this.paswdProfile$.subscribe(res => {this.paswdProfile = res[0]})
    console.log(this.paswdProfile)
}

createPasswordForm(): FormGroup {
    return this.fb.group(
      {
        oldPassword : [ null, Validators.compose([Validators.required])],
        newPassword: [
          null,
          Validators.compose([
            Validators.required,
            // check whether the entered password has a number
            CustomValidators.patternValidator(/\d/g, this.paswdProfile.numbers , {
              hasNumber: true
            })
          ])
        ],
      },
    );
}


【问题讨论】:

  • 你能提供一些代码吗?
  • 我用一些代码更新了问题
  • 所以您想根据您的响应为表单分配初始值?如果不能,请您准确指出在哪里看?

标签: angular


【解决方案1】:

我想我找到了解决方案,我在表单中添加了一个默认为 false 的 hasData。然后为了使它工作,我将 createPasswordForm 以及 this.hasData = true 添加到订阅中。在模板上我添加了 *ngIf="hasData" 所以模板只在有数据时呈现。

this.paswdProfile$.subscribe(res => {this.paswdProfile = res, 
                                        this.passwordForm = this.createPasswordForm(), this.hasData = true})

【讨论】:

    【解决方案2】:

    在验证器中,您可以检查 observable 是否已经存在。如果不返回 null(无错误)。在设置期间,它不会验证,但验证器不必验证任何东西,所以这没问题。在使用表单期间,订阅将存在,因此应用您的逻辑。

    【讨论】:

      【解决方案3】:
      paswdProfile$: Observable<IPasswordProfile>
      paswdProfile: IPasswordProfile
      
      constructor(@Inject(MAT_DIALOG_DATA) public data: any, private dialogRef: MatDialogRef<PasswordComponent>,
              private adminService: AdminService, private route: ActivatedRoute, private cbLookupService: CouchbaseLookupService,
              private router: Router, private dialog: MatDialog, private toasterService: ToasterService, private fb: FormBuilder) {
      
          this.passwordForm = this.createPasswordForm()
      }
      
      
      
      ngOnInit() {
          this.paswdProfile$ = this.adminService.getPasswordProfile("8084ea42-633e-4c28-bc7a-372aa58a4d1c")
          this.paswdProfile$.subscribe(res => {this.paswdProfile = res[0]})
          console.log(this.paswdProfile)
      }
      
      createPasswordForm(): FormGroup {
          return this.fb.group(
            {
              oldPassword : [ null, Validators.compose([Validators.required])],
              newPassword: [
                null,
                Validators.compose([
                  Validators.required,
                  // check whether the entered password has a number
                  this.anAsyncValidator.bind(this)
                ])
              ],
            },
          );
      }
      
      anAsyncValidator(c: any) {
          return Observable.create(observer => {
              this.paswdProfile$.subscribe(res => {
                  this.paswdProfile = res[0]
                  observer.next(CustomValidators.patternValidator(
                       /\d/g, 
                       this.paswdProfile.numbers , 
                       {
                           hasNumber: true
                       })(c)
                  )
              })
          })
      }
      

      此代码可能不完全有效,但至少应该让您了解使用自定义异步验证器解决问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-19
        • 1970-01-01
        • 2020-11-14
        • 1970-01-01
        相关资源
        最近更新 更多