Michael Pell
Michael Pell

Reputation: 1476

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

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?

Upvotes: 1

Views: 475

Answers (1)

chrisbajorin
chrisbajorin

Reputation: 6153

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.

Upvotes: 1

Related Questions