【问题标题】:Why Ionic sometines need a timeout to deal with components为什么 Ionic sometines 需要超时来处理组件
【发布时间】:2019-03-16 09:13:12
【问题描述】:

我经常需要添加一个 setTimeout 来让 Ionic 以正确的方式运行指令。

我的配置:

Ionic:

   ionic (Ionic CLI)  : 4.0.1 (/Users/rguerin/.nvm/versions/node/v6.10.1/lib/node_modules/ionic)
   Ionic Framework    : ionic-angular 3.1.1
   @ionic/app-scripts : 1.3.7

System:

   NodeJS : v6.10.1 (/Users/rguerin/.nvm/versions/node/v6.10.1/bin/node)
   npm    : 3.10.10
   OS     : macOS High Sierra

我的模板:

<ion-list [formGroup]="formGroup">

    <ion-item *ngIf="countries">

        <ion-label floating>
            {{ 'customer.country' | translate }}
            <span class="required" ion-text color="red">*</span>
        </ion-label>

        <ion-select formControlName="Country">
            <ion-option *ngFor="let c of countries" [value]="c.In">{{c.Out}}</ion-option>
        </ion-select>

    </ion-item>

例如,如果我尝试像这样设置表单控件值,如果没有 setTimeout,它将无法正常工作:

private setFormControlValue(propertyName: string, value: string, stockEmpty?: boolean): void {

    let formControl: AbstractControl = this.formGroup.controls[propertyName];
    if (_.isEmpty(value) && !stockEmpty) {
        return;
    } else {
        if (!_.isEmpty(formControl) && !_.isNil(formControl)) {
            this.logger.trace('Setting value %s for control : ', value, formControl);
            setTimeout(() => formControl.setValue(value), 100);
        }
    }
}

当我想调整我的内容大小时也会发生:

ngOnInit(): void {

    setTimeout(() => this.content.resize(), 100);
}

它有时甚至可以在“0”毫秒的超时下工作。我想避免在任何地方使用超时,但我的印象是 Ionic 需要在不同的“线程”中运行指令才能以正确的方式执行。

如果有人遇到同样的问题或知道更好的解决方法,我很乐意接受。

【问题讨论】:

  • 你在哪个活动做这个?
  • 这在 ngOnInit() 方法中,但我的代码中几乎到处都有这个问题
  • 不在 ngOnInit() 内部,它由用户操作触发(单击选定的组件)。我没有显示其余代码,因为此方法的行为不应该受到它的影响。
  • 你能看看this answer吗?
  • 也很有意思,谢谢分享!

标签: angular typescript ionic-framework ionic3


【解决方案1】:

根据我的经验,setTimeout 有时会在 DOM 操作和 DeviceReady 函数方面发挥作用。 我觉得这主要归功于 Angulardigest-loop 性能。

这里是stackoverflow 的post 有点旧,而且写得很好。

感谢您阅读我糟糕的回答。

【讨论】:

  • 这是完全一样的行为,我会继续。非常感谢您,非常有趣的阅读。
【解决方案2】:

你试过了吗:

this.formGroup.get('Country').setValue('toto');

立即为我工作

【讨论】:

  • 感谢您的回答,但我的问题有点笼统。我用 formGroup 做了这个例子,但它也发生在其他组件上。我更新了我的第一篇文章。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-14
  • 2017-12-04
  • 2011-05-10
相关资源
最近更新 更多