嗨,我得到了一个函数,它将在向服务器发出 http 请求后更新。控制台似乎.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>
有什么方法可以解决这个问题吗?谢谢
尝试将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:");
});
}
}
我在 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。