您好我有一个功能,它会在向服务器发出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:");
})
这是我的观点html:
<ion-row>
<ion-col center width-100 no-padding>
<h2>{{sv_value}}</h2> //This is not updated
</ion-col>
</ion-row>
我有什么方法可以解决这个问题吗?谢谢
答案 0 :(得分:23)
尝试将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:");
});
}
}
答案 1 :(得分:0)
我在Ionic 4中面临着完全相同的问题,这就是我如何解决它:
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:");
})
本质上,通过使用detectChanges()
,我们迫使平台检测更改并将其踢入UI。