即使手动运行更改检测,视图中的变量也不会在Angular中更新

问题描述

我经历了很多与此类似的堆栈溢出问题,但仍然找不到解决方案。我正在以反应形式使用自定义异步验证器,该验证器正在调用函数showToaster()。 在showToaser()内部,我正在将标志this.showToasMsg设置为true。但是,它没有更新。就是说,奇特的事情是我第一次访问页面时,视图正在更新。但是,如果我返回上一页并再次返回,即使该组件中的案例视图有所更改,该案例视图也不会更新。

表单初始化代码

verificationForm = this.fb.group({
    appointmentDetails: this.fb.group({
      bookingReferenceNo: ['',Validators.required],classification: ['',cargoType: ['',serviceType: ['',appointmentDate: ['',appointmentTimeSlot: [
        '',{
          asyncValidators: [this.timeSlotValidationhandler.bind(this)],updateOn: 'blur',validators: [Validators.required]
        }
      ],cargoDetails: ['']
    }),repDetails: this.fb.array([this.createRep()]),documents: this.fb.array([this.createDoc()])
  });

//方法,用于创建代表详细信息字段,在表单初始化时会调用该字段

createRep(): FormGroup {
    console.log('createRep');
    return this.fb.group({
      repName: ['',passport: [
        '',{
          asyncValidators: [
            this.repValidate.bind(this)
          ],phoneNumber: [
        '',{
          asyncValidators: [this.checkDuplicateRep.bind(this)],validators: [Validators.required]
        }
      ]
    });
  }

调用showToaster()的自定义验证功能

repValidate(control: AbstractControl) {
    console.log('repValidate');
    return new Promise(resolve => {
      if (
        !control.pristine &&
        this.verificationService.paramValue === AppConstants.ParaM_VALUE_Y
      ) {
        const queryParam = {
          passportNo: control.value,accesstoken: this.verificationService.accesstoken
        };
        this.verificationService
          .validateRep(queryParam)
          .subscribe((data: any) => {
            if (data.responseCode === AppConstants.ERROR_CODE) {
              this.responseMsg = data.responseMessage;
              this.showToaster();
              //this.cdRef.detectChanges();
              //this.apRef.tick();
              resolve({ passportErr: control.value });
            } else {
              resolve(null);
            }
          });
      } else {
        resolve(null);
      }
    });
  }

然后,下面是显示烤面包机的功能

showToaster() {
    this.showToastMsg = true;
    this.failureFlag = true;
    this.timeoutObj = setTimeout(() => {
      this.showToastMsg = false;
      this.failureFlag = false;
    },5000);
  }

当我在此消息中合并此值时,它会将 this.showToastMsg 的值打印为true。但是,如果我从模板调用click事件并尝试控制相同的值,则该值未定义。而且,奇怪的是,仅当我初始化一次verifyForm,然后返回到上一页并再次返回时,这种情况才会发生。

我认为angular无法检测到变化。所以我尝试手动关注,

  • ApplicationRef.tick()
  • ngzone.run(回调)
  • ChangeDetectorRef.detectChanges()

任何帮助将不胜感激。谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)