Roland Le Franc
Roland Le Franc

Reputation: 356

How to access component properties from within an observer's handler?

How can I access my component properties (variables and methods) from within the observer handler of an observable? I've read many examples on observables but all they do in the handlers is console.log() which is not very useful in real life (e.g. https://angular.io/guide/observables).

I would like to synchronize an action in my component when the observable is complete.

export class MyComponent {
  // Create simple observable that emits three values
  const myObservable = of(1, 2, 3);
  private myProperty = false;

  private myObserver = {
    next(position) {
      console.log('position: ', position);
    }
    complete() {
      this.myProperty = true;
    }
  }

  constructor() {
    myObservable.subscribe(myObserver);
  }
}

When I execute this, I get that this.myProperty is undefined.

Thank you

Upvotes: 0

Views: 375

Answers (1)

yurzui
yurzui

Reputation: 214335

I think you can go with arrow functions to preserve this context:

private myObserver = {
  next: (position) => {
    console.log('position: ', position);
  },
  complete: () => {
    this.myProperty = true;
  }
}

Upvotes: 6

Related Questions