Reputation: 25
I have an event listener that uses firebase functions in it. in the case the file is being uploaded and upon completion I want it to run a function found in another file. The code in the other file works as it works in the onInit().
code:
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 => {}));
});
});
};
The issue is with "((FileuploadComponent) => this.auth.sendFileStruct({msg: 'hello'}).subscribe(data => {}));"
It doesn't run auth.sendFileStruct
Upvotes: 1
Views: 47
Reputation: 333
You have defined a function that should be called immediately, so you have to do like this:
// add the parenthesis at the end
((FileuploadComponent) => this.auth.sendFileStruct({msg: 'hello'}).subscribe(data => {}))();
Or get the function into a variable and call it by the current this object
Upvotes: 1
Reputation: 10778
this
inside a function declared with the keyword function
references the function, no longer the class. You can either use arrow function like that:
task.on('state_changed',
snapshot => {/*progress function content*/},
err => {/*error function content*/},
...
);
Or less elegantly bind this
in a variable to keep the reference.
var that = this;
...
that.auth.sendFileStruct(...)
Upvotes: 2