javascript - 如何在回调函数中保留 'this' 实例

标签 javascript angular typescript

在 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/

相关文章:

javascript - Angular 默认下拉值 2 向绑定(bind)

javascript - 有没有办法将 IndexedDB 记录设为 "watch",以便我可以在更改时做出响应?

function - typescript 从传递的函数返回类型推断返回类型

javascript - 在knockoutjs组件中实现继承

javascript - 有没有办法将 javascript 应用到一个输入字段?

angular - 如何在 Angular2 中注销时获取新实例/重新加载所有服务

javascript - 类型错误 : Cannot read property '_rawValidators' of null after Ng build

javascript - 防止父组件状态改变后子组件状态重置同时获取所有子组件的值:ReactJS+ Typescript

javascript - 单击图像打开/弹出文件字段

angular - 在哪里可以找到特定版本的文档