【发布时间】: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