Ionic 3没有更新视图

Red*_*tif 18 cordova ionic-framework ionic2 ionic3 angular

嗨我有一个功能,它会在http请求到服务器后更新.似乎console.log显示该值已更新但UI未更新,除非我单击任何其他组件(例如输入).

这是我的功能:

fileTransfer.upload(this.created_image, upload_url, options)
.then((data) => {
    console.log("success:"+data.response); //This is showing correct response
    var obj = JSON.parse(data.response);
    this.sv_value = obj.value;
    console.log(this.sv_value); //This is showing correct value
}, (err) => {
    console.log("failure:");
})
Run Code Online (Sandbox Code Playgroud)

这是我的观点html:

    <ion-row>
      <ion-col center width-100 no-padding>
        <h2>{{sv_value}}</h2> //This is not updated
      </ion-col>
    </ion-row>
Run Code Online (Sandbox Code Playgroud)

有什么办法可以解决这个问题吗?谢谢

rob*_*nnn 28

尝试放入this.sv_value = obj.value;内部NgZone.run();以使Angular检测到更改.

import { Component, NgZone } from "@angular/core";
...

export class MyComponentPage {
    constructor(
        private zone: NgZone
        ...
    ){ }

    yourFunction(){
        fileTransfer.upload(this.created_image, upload_url, options)
        .then((data) => {
            console.log("success:"+data.response); //This is showing correct response
            var obj = JSON.parse(data.response);

            this.zone.run(() => {
                this.sv_value = obj.value;
            });

            console.log(this.value); //This is showing correct value
        }, (err) => {
            console.log("failure:");
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @RedzwanLatif这仍然是您的解决方案吗?就我而言,仅当我们在移动设备上使用该视图时,该视图才会呈现,离子服务没有问题,您是否有相同的行为? (3认同)

Dev*_*ner 8

I was facing the exact same issue in Ionic 4 and this is how I fixed it:

import { ChangeDetectorRef } from '@angular/core';

constructor(private changeRef: ChangeDetectorRef)

fileTransfer.upload(this.created_image, upload_url, options)
.then((data) => {
    console.log("success:"+data.response); //This is showing correct response
    var obj = JSON.parse(data.response);
    this.sv_value = obj.value;
    console.log(this.sv_value); //This is showing correct value
    this.changeRef.detectChanges(); // ---> Add this here
}, (err) => {
    console.log("failure:");
})
Run Code Online (Sandbox Code Playgroud)

Essentially by using detectChanges(), we are forcing the platform to detect the changes and kick them into the UI.