我正在制作一款带有Ionic的应用,可将图片上传到我的Firebase存储空间。上传完成后,应用程序应将用户重定向到WelcomePage。上传工作正常,但由于某种原因,用户未被重定向。看一下代码的结尾:控制台确实显示Uploaded
,但this.navCtrl.push(WelcomePage)
无效。
upload() {
let storageRef = firebase.storage().ref();
const filename = "profilePic";
const imageRef = storageRef.child(`images/${filename}.jpg`).putString(this.profilepicture, firebase.storage.StringFormat.DATA_URL);
imageRef.on('state_changed', function(snapshot){
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
document.getElementById("percent").innerHTML = "Progresso:" + Math.floor(progress) + "%";
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED:
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING:
console.log('Upload is running');
break;
}
}, function(error) {
// Handle unsuccessful uploads
}, function() {
// Handle successful uploads on complete
console.log('Uploaded');
this.navCtrl.push(WelcomePage);
});
}
答案 0 :(得分:2)
this
的含义很可能在您的回调中有所不同。如果是这种情况,您可以将navCtrl
放在单独的变量中,也可以使用胖箭头函数。
navCtrl
放在单独的变量 this
的含义取决于您使用它的函数。由于回调是单独的函数,它们也有this
的值。所以回调内部this.navCtrl
不存在。
解决方案是在回调之前将所需的值捕获到唯一的变量名称中:
var navCtlr = this.navCtrl;
imageRef.on('state_changed', function(snapshot){
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
document.getElementById("percent").innerHTML = "Progresso:" + Math.floor(progress) + "%";
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED:
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING:
console.log('Upload is running');
break;
}
}, function(error) {
// Handle unsuccessful uploads
}, function() {
// Handle successful uploads on complete
console.log('Uploaded');
navCtrl.push(WelcomePage);
});
ES6添加了一种使用胖箭头表示法定义回调函数的新方法。在您的代码中,function(error) {
可以替换为(error) => {
。除了稍微缩短之外,新的表示法实际上保留了回调中this
的含义。所以:
imageRef.on('state_changed', (snapshot) => {
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
document.getElementById("percent").innerHTML = "Progresso:" + Math.floor(progress) + "%";
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED:
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING:
console.log('Upload is running');
break;
}
},(error) => {
// Handle unsuccessful uploads
}, () => {
// Handle successful uploads on complete
console.log('Uploaded');
this.navCtrl.push(WelcomePage);
});