In Angular2, I have a component that uses a service to upload a file to Amazon S3.
My component (simplified):
private _loading = true;
// use service to upload file
this._s3service.uploadFile(fileObject, this.uploadCallback)
// use this function as a callback
uploadCallback(err, data) {
this._loading = false; // this crashes because of 'this' is referring to service instead of component
}
My service (simplified):
private getS3(): any {
return s3;
}
public uploadFile(selectedFile, callback): boolean {
this.getS3().upload({
Key: key_name,
ContentType: file.type,
Body: file,
StorageClass: 'STANDARD',
ACL: 'private'
}, function(err, data){
callback(err, data)
});
}
The problem is that when the callback function is started from the service, it thisrefers to the service and this._loadingcannot be found.
Question: How to save an instance thisin my callback function, ( thisin the callback should point to component, not service)
source
share