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

458 views Asked by At

I am working in an NG2 app using TypeScript and want to create an observable around a call to Amazon AWS SDK.

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

Unfortunately, this is now bound to the Observable. How should I approach this if I want this to remain bound to the parent class?

1

There are 1 answers

0
chrisbajorin On BEST ANSWER

You can just wrap the observer function and bind your outside this to it:

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

It's important to make sure the wrapped function is a classic function and not an arrow function, or this within the function will end up being the window.