RangeError: Maximum call stack size exceeded when using valueChanges.subscribe

RangeError: Maximum call stack size exceeded when using valueChanges.subscribe

我正在使用 Angular 5 和 Reactive 表单,需要使用 valueChanges 来动态禁用所需的验证

组件class:

export class UserEditor implements OnInit {

    public userForm: FormGroup;
    userName: FormControl;
    firstName: FormControl;
    lastName: FormControl;
    email: FormControl;
    loginTypeId: FormControl;
    password: FormControl;
    confirmPassword: FormControl;
...

ngOnInit() {
    this.createFormControls();
    this.createForm();
    this.userForm.get('loginTypeId').valueChanges.subscribe(

            (loginTypeId: string) => {
                console.log("log this!");
                if (loginTypeId === "1") {
                    console.log("disable validators");
                    Validators.pattern('^[0-9]{5}(?:-[0-9]{4})?$')]);
                    this.userForm.get('password').setValidators([]);
                    this.userForm.get('confirmPassword').setValidators([]);

                } else if (loginTypeId === '2') {
                    console.log("enable validators");
                    this.userForm.get('password').setValidators([Validators.required, Validators.minLength(8)]);
                    this.userForm.get('confirmPassword').setValidators([Validators.required, Validators.minLength(8)]);

                }

                this.userForm.get('loginTypeId').updateValueAndValidity();

            }

        )
}
createFormControls() {
    this.userName = new FormControl('', [
        Validators.required,
        Validators.minLength(4)
    ]);
    this.firstName = new FormControl('', Validators.required);
    this.lastName = new FormControl('', Validators.required);
    this.email = new FormControl('', [
      Validators.required,
      Validators.pattern("[^ @]*@[^ @]*")
    ]);
    this.password = new FormControl('', [
       Validators.required,
       Validators.minLength(8)
    ]);
    this.confirmPassword = new FormControl('', [
        Validators.required,
        Validators.minLength(8)
    ]);

}

createForm() {
 this.userForm = new FormGroup({
      userName: this.userName,
      name: new FormGroup({
        firstName: this.firstName,
        lastName: this.lastName,
      }),
      email: this.email,
      loginTypeId: this.loginTypeId,
      password: this.password,
      confirmPassword: this.confirmPassword
    });
}

然而,当我 运行 它时,我得到一个浏览器 javascript 错误

UserEditor.html:82 ERROR RangeError: Maximum call stack size exceeded
    at SafeSubscriber.tryCatcher (tryCatch.js:9)
    at SafeSubscriber.webpackJsonp.../../../../rxjs/_esm5/Subscription.js.Subscription.unsubscribe (Subscription.js:68)
    at SafeSubscriber.webpackJsonp.../../../../rxjs/_esm5/Subscriber.js.Subscriber.unsubscribe (Subscriber.js:124)
    at SafeSubscriber.webpackJsonp.../../../../rxjs/_esm5/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:242)
    at SafeSubscriber.webpackJsonp.../../../../rxjs/_esm5/Subscriber.js.SafeSubscriber.next (Subscriber.js:186)
    at Subscriber.webpackJsonp.../../../../rxjs/_esm5/Subscriber.js.Subscriber._next (Subscriber.js:127)
    at Subscriber.webpackJsonp.../../../../rxjs/_esm5/Subscriber.js.Subscriber.next (Subscriber.js:91)
    at EventEmitter.webpackJsonp.../../../../rxjs/_esm5/Subject.js.Subject.next (Subject.js:56)
    at EventEmitter.webpackJsonp.../../../core/esm5/core.js.EventEmitter.emit (core.js:4319)
    at FormControl.webpackJsonp.../../../forms/esm5/forms.js.AbstractControl.updateValueAndValidity (forms.js:3377)

"log this!" 被重复调用,就像它被递归调用一样,这就是为什么它们是堆栈错误

如果我删除 valueChanges.subscribe 代码除了有条件地删除验证之外的工作。

为什么递归调用valueChanges.subscribe?

尝试在 subscribe() 之前的管道中添加 distinctUntilChanged()。它应该过滤掉那些 "change" 值实际上没有改变的事件。

问题是您修改了同一字段的 valueChanges 事件处理程序中的字段值,导致事件再次被触发:

this.userForm.get('loginTypeId').valueChanges.subscribe(
  (loginTypeId: string) => {
    ...
    this.userForm.get('loginTypeId').updateValueAndValidity(); <-- Triggers valueChanges!
}

如果您想订阅任何表单更改并且仍然在其中 运行 patchValue,那么您可以将 {emitEvent: false} 选项添加到 patchValue,这样补丁将不会触发另一个更改检测

代码:

this.formGroup
    .valueChanges
    .subscribe( _ => {
        this.formGroup.get( 'controlName' ).patchValue( _val, {emitEvent: false} );
    } );

PS。这也比一个一个地订阅每个表单控件以避免触发更改最大调用堆栈超出的繁琐。特别是如果您的表单有 100 个要订阅的控件。

现在进一步详细说明,如果您仍然需要在订阅内部更新 ValueAndValidity,那么我建议您使用 distinctUntilChanged rxjs 运算符,以便仅 运行 订阅,当某些值发生变化时。

可在此处找到 distinctUntilChanged 文档

https://www.learnrxjs.io/operators/filtering/distinctuntilchanged.html

distinctUntilChanged - Only emit when the current value is different than the last.

现在我们还必须将其设为自定义验证函数,因为默认情况下,distinctUntilChanged 通过指针验证对象,并且指针在每次更改时都是新的。

this.formGroup
    .valueChanges
    .distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b))
    .subscribe( _ => {
        this.formGroup.get( 'controlName' ).patchValue( _val, {emitEvent: false} );
        this.formGroup.get( 'controlName' ).updateValueAndValidity();
    } );

瞧,我们正在修补和更新,没有 运行进入最大调用堆栈!

我的回答只是的发展。

通过在 subscribe() 之前的管道中添加 distinctUntilChanged() 可以避免“超出最大调用堆栈大小”,因为

distinctUntilChanged method only emit when the current value is different than the last.

用法:

this.userForm.get('password')
  .valueChanges.pipe(distinctUntilChanged())         
  .subscribe(val => {})

Documentation

我在验证时遇到了类似的错误。调用 updateValueAndValidity() 时出现错误。在我的例子中,我使用了这个重载 updateValueAndValidity({emitEvent : false})

试试这个

this.userForm.get('loginTypeId').updateValueAndValidity({emitEvent : false});

this.userForm.get('loginTypeId').enable({emitEvent: false});

如果您需要启用所有 select 表单中的一个 select