我有一个使用firebase函数的事件监听器。在文件上传的情况下,完成后我希望它运行在另一个文件中找到的功能。另一个文件中的代码在onInit()中起作用。
代码:
fileButton.addEventListener('change', (e: any) => {
//gets the path of the file they want to upload
var filePath= (<HTMLInputElement>document.getElementById('filePathInp')).value;
//get file:
var file = e.target.files[0];
//get ID of user
var user = JSON.parse(localStorage.getItem('user'));
// Create a storage reference
if (filePath != ''){
var ref = (user.id) + '/'+ filePath + '/' + file.name;
} else {
var ref = (user.id) + '/' + file.name;
}
var storageRef = firebase.storage().ref(ref);
//Upload file
var task = storageRef.put(file);
//update progress bar
task.on('state_changed',
function progress(snapshot){
//calculate the percentage
var percentage = (task.snapshot.bytesTransferred / task.snapshot.totalBytes) * 100;
//display the percentage completed
uploader.value = String(percentage);
},
function(err){
//throw error if error occurs
throw(err);
},
function complete(){
//upon completion console log
console.log('COMPLETE!!');
((FileuploadComponent) => this.auth.sendFileStruct({msg: 'hello'}).subscribe(data => {}));
});
});
};
&#13;
问题在于 &#34;((FileuploadComponent)=&gt; this.auth.sendFileStruct({msg:&#39; hello&#39;})。subscribe(data =&gt; {}));&#34;
它没有运行auth.sendFileStruct
答案 0 :(得分:2)
this
声明的函数内的 function
引用该函数,不再是类。您可以使用箭头功能:
task.on('state_changed',
snapshot => {/*progress function content*/},
err => {/*error function content*/},
...
);
或者不太优雅地在变量中绑定this
以保留引用。
var that = this;
...
that.auth.sendFileStruct(...)
答案 1 :(得分:1)
你已经定义了一个应该立即调用的函数,所以你必须这样做:
// add the parenthesis at the end
((FileuploadComponent) => this.auth.sendFileStruct({msg: 'hello'}).subscribe(data => {}))();
或者将函数放入变量并通过当前此对象调用它