-1

I have an observable which returns a value that I need to manipulate in a function, so I thought it would be cleaner if I just sent the function as a callback instead of creating a new anonymous function. However I made the change and I started getting this error message: Error: Cannot set properties of undefined (setting 'name').

STACKBLITZ DEMO

  ngOnInit(): void {
     this.updateName('First New Name!');

     of('Second New Name!')
     .pipe(delay(1500))
     // .subscribe(name => this.updateName(name)); // Works!
     .subscribe(this.updateName); // Doesn't work - Error: Cannot set properties of undefined (setting 'name')
  }

  updateName(name: string): void {
      this.name = name;
  }

Is it supposed to work this way? Why is this happening?

juan_carlos_yl
  • 641
  • 8
  • 14

1 Answers1

1

Switch updateName to lambda/arrow function.

updateName = (name: string) => {
  this.name = name;
}

Sample Demo on StackBlitz


According to Arrow function expressions, arrow function doesn't own this.

Arrow functions establish "this" based on the scope the Arrow function is defined within.

Hence, the arrow function works as

this is looked up in scope just like a normal variable.

Credited from: @Felix's answer on How to access the correct this inside a callback

Yong Shun
  • 35,286
  • 4
  • 24
  • 46