playAudio(index){
storageRef.getDownloadURL().then(onResolve, onReject);
function onResolve() {
storageRef.getDownloadURL().then(function(url) {
console.log(url);
sMedia.playAudio(url);
})
console.log("File found!")
}
function onReject() {
this.presentAlert(); /* <---- This is the problem */
console.log("File don't exist.")
}
presentAlert() {
let alert = this.alertCtrl.create({
title: 'Ops!',
subTitle: "No file for this search",
buttons: ['OK']
});
alert.present();
}
此代码似乎有效。如果该文件存在于Firebase上,则函数onResolve()可以正常工作。相反,如果该文件不存在,则会显示控制台日志,但功能不会执行。
这是因为函数presentAlert()在函数onReject()中不可见。为什么? 我该如何解决这个问题?
答案 0 :(得分:0)
我的直觉说这取决于这个参考。尝试不带this的代码,和/或使用箭头功能保留其绑定。例如。 (使用内联方法)
storageRef.getDownloadURL().then(() => {
storageRef.getDownloadURL().then(function(url) {
console.log(url);
sMedia.playAudio(url);
})
console.log("File found!");
}).catch((e) => {
this.presentAlert(); /* <---- >this< is the problem */
console.log("File don't exist.")
});
function presentAlert() {
let alert = this.alertCtrl.create({
title: 'Ops!',
subTitle: "No file for this search!",
buttons: ['OK']
});
alert.present();
}
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/this