我在Angular2中使用此功能(cordova插件的一部分):
download()
{
//some download stuff
// ==> here this.percentage=50 works
//show progress of download
this.fileTransfer.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
console.log((progressEvent.loaded / progressEvent.total)); // works great
this.setpercentage((progressEvent.loaded/progressEvent.total)*100) // doesn't work
} else {}
}
}
setpercentage(perc)
{
this.percentage = perc;
}
但percentage
并未更新。它说setpercentage()
不是函数。
我是Angular的新手,我已经读过有关箭头功能的地方了。所以我试了一下,把它改成了:
this.fileTransfer.onprogress((progressEvent)=>{
if (progressEvent.lengthComputable) {
console.log((progressEvent.loaded / progressEvent.total));
this.setpercentage((progressEvent.loaded/progressEvent.total)*100)
} else {}
});
但这打破了整个剧本。控制台日志不再显示百分比。
我做错了什么?
更新:我尝试了@echonax
建议,但没有运气:
download()
{
this.setpercentage(50); <-- works
this.fileTransfer.download(**download stuff**);
var self = this; // store outer this in a variable
this.fileTransfer.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
console.log((progressEvent.loaded / progressEvent.total)); // works great
self.setpercentage(60); // <-- doesn't work
} else {}
}
}
setpercentage(perc)
{
this.percentage = perc;
}
答案 0 :(得分:3)
更改
this.fileTransfer.onprogress = function(progressEvent) {
到
this.fileTransfer.onprogress = (progressEvent)=> {
您的this
未提及您的组件
这类似于做
var self = this; // store outer this in a variable
this.fileTransfer.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
console.log((progressEvent.loaded / progressEvent.total)); // works great
self.setpercentage(60, self) // <-- use it here
} else {}
}
setpercentage(perc, self)
{
setTimeout(()=>{
self.percentage = perc;
},0);
}
但是使用第二种方法,this
方法中的setpercentage
将引用函数实例而不引用组件
答案 1 :(得分:0)
作为pointed out by rapropos,在修改控制器的ChangeDetectorRef
属性后注入detectChanges()
并调用其percentage
方法,可以解决此问题!