在Angular2中,我有一个使用服务将文件上传到Amazon S3的组件。如何在回调函数中保留'this'实例
我的组分(简化):
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
}
我的服务(简化):
private getS3(): any {
// Get or create AWS instance
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){ // <=== What to do here?!
callback(err, data)
});
}
的问题是,当所述回调函数从服务触发,this
指的是服务和this._loading
无法找到。
问:我怎样才能保持this
比如在我的回调函数,(this
在回调必须指向component
而不是service
)
可能的解决方法也可能是使用实例函数的https:// github上。 com/Microsoft/TypeScript/wiki /%27this%27-in-TypeScript#use-instance-functions – yurzui