在 Angular2 中,我有一个组件使用服务将文件上传到 Amazon S3。
我的组件(简化):
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
)
最佳答案
使用箭头函数
}, (err, data) => { // <=== What to do here?!
它们正是为了这个目的,让 this
一直指向声明函数的类实例。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
如果你传递一个函数引用 .bind(this)
可能会更方便,因为它根本不需要列出参数,而 = >
需要它们两次
myCallback(err, data){ // <=== What to do here?!
callback(err, data)
}
public uploadFile(selectedFile, callback): boolean {
this.getS3().upload({
Key: key_name,
ContentType: file.type,
Body: file,
StorageClass: 'STANDARD',
ACL: 'private'
}, this.myCallback.bind(this));
}
与箭头功能相同
public uploadFile(selectedFile, callback): boolean {
this.getS3().upload({
Key: key_name,
ContentType: file.type,
Body: file,
StorageClass: 'STANDARD',
ACL: 'private'
}, (err, data) => this.myCallback(err, data));
}
关于javascript - 如何在回调函数中保留 'this' 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42854090/