gpt4 book ai didi

typescript - navCtrl.push 在 Ionic3 中不起作用

转载 作者:搜寻专家 更新时间:2023-10-30 21:39:30 25 4
gpt4 key购买 nike

我正在使用 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);
});

}

最佳答案

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);
});

关于typescript - navCtrl.push 在 Ionic3 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45265994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com