在 RxJS (TypeScript) 5.0 中创建不绑定到 `this` 的观察者

Creating Observer in RxJS (TypeScript) 5.0 that does not bind to `this`

我正在使用 TypeScript 在 NG2 应用程序中工作,并希望围绕对 Amazon AWS SDK 的调用创建一个可观察对象。

var foo =  Observable.create( (observer) => {
  this.s3.upload({
    Key: "value"
  }, (err, data) => {
    if (err) {
      console.log(err)
      return
    }
    observer.next(data)
  });
})

不幸的是,this 现在绑定到 Observable。如果我希望 this 与父 class 保持绑定,我应该如何处理?

您可以只包装观察者函数并将外部 this 绑定到它:

var foo = Observable.create((function(observer) {
  this.s3.upload({
    Key: "value"
  }, (err, data) => {
    if (err) {
      console.log(err);
      return
    }
    observer.next(data)
  });
}).bind(this));

确保包装函数是经典函数而不是箭头函数很重要,否则函数中的 this 最终会成为 window.