【问题标题】:Navigating to a page in a custom event doesn't work properly导航到自定义事件中的页面无法正常工作
【发布时间】:2018-08-27 17:38:54
【问题描述】:

当我使用此事件导航到页面时:

this.events.subscribe('liveTrackingEvent', (time, unit) => {
        console.log("event triggered");
        this.searchForm.controls['unitID'].setValue(this.unitSelected.unit.name);
        this.GetLiveData();
    });

一切都被调用,函数 GetLiveData() 也是如此。 (我没有发布这个函数的代码,因为它无关紧要)

但是,当我查看页面时,没有 1 个元素在更新。所以这一行:

this.searchForm.controls['unitID'].setValue(this.unitSelected.unit.name);

不更新 searchform 控件,但是当我从页面本身调用这行代码而没有在另一个页面上触发事件时,它可以顺利运行并更新 searchform 控件。

(就像我出于某种原因在单独的线程上一样),我把它放在括号之间,因为它只是一个想法。

所以我的问题是:如何在事件触发时强制此页面自行更新?

提前致谢,如果你们需要更多代码,尽管问,但这是最相关的代码,因为一切都在工作,只是在事件内部调用时没有。

【问题讨论】:

    标签: html typescript ionic-framework ionic2 ionic3


    【解决方案1】:

    我只能想到这种行为的 1 个原因。您正在 Angular Zone 之外更新您的表单。这就是未检测到更改的原因。

    为了解决这个问题,将最后两行事件的调用包装成“this.ngZone.run(() => { ... })”。

    例如

        this.events.subscribe('liveTrackingEvent', (time, unit) => {
                console.log("event triggered");
                this.ngZone.run(()=>{            
    
           this.searchForm.controls['unitID'].setValue(this.unitSelected.unit.name);
                this.GetLiveData();
    });
            });
    

    【讨论】:

    • 谢谢,这也解决了问题,但我坚持我的解决方案。
    【解决方案2】:

    通过使用页面生命周期事件而不是来自 ionic 框架的自定义事件,我设法完成了这项工作,甚至获得了更简洁的代码。 示例:

    第一页:

    GoToLiveTracking(unitID){
        this.navCtrl.push(MapPage, {redirected: true, unitID: unitID});
    }
    

    第二页:

    ionViewDidEnter(){
        if(this.navParams.get('redirected')){
            let unit_id = this.navParams.get('unitID');
            this.unitSelected = this.completeService.GetUnitByID(unit_id);
            this.searchForm.controls['unitID'].setValue(this.unitSelected.unit.name);
            this.GetLiveData();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-30
      • 1970-01-01
      • 2015-08-26
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 2017-02-10
      • 2019-03-13
      • 1970-01-01
      相关资源
      最近更新 更多