edmond tm
edmond tm

Reputation: 59

Not able to access variable outside of second function in reactive programming

I have 2 Javascript functions. The first returns value to the second. In the second function, I am not able to access a constant declared earlier.

I have tried renaming the constant.

//app.service.ts

import { Injectable, OnModuleInit } from '@nestjs/common';
import { Observable, of } from 'rxjs';

@Injectable()

export class AppService implements OnModuleInit {

  constant1 = 'constant1';

  onModuleInit() {
    this.someFunction1()
    .pipe(
      this.someFunction2,
    ).subscribe(console.log);
  }

  private someFunction1(): Observable<string> {
    console.log('someFunction1');
    console.log('constant1 = ', this.constant1);
    return of('done');
  }

  private someFunction2(something:Observable<string>):Observable<string> {
    console.log('someFunction1');
    console.log('constant1 = ', this.constant1); 
    // Cannot read property of constant1
    return of('done');
  }

}

I expect the output is 'constant1'. But I get an error of 'cannot read property of constant1.'

Upvotes: 2

Views: 299

Answers (2)

Kim Kern
Kim Kern

Reputation: 60377

This is because this is not bound to the AppService because of its invocation:

onModuleInit() {
  this.someFunction1()
    // You are passing someFunction2 as a function expression
    .pipe(this.someFunction2)
    .subscribe(console.log);
}

Instead pass someFunction2 as an arrow function where this is lexically bound, meaning that whatever this is for the caller of the arrow function it will be the same within the arrow function:

onModuleInit() {
  this.someFunction1()
    .pipe(something => this.someFunction2(something))
    .subscribe(console.log);
}

Upvotes: 1

Fan Cheung
Fan Cheung

Reputation: 11345

try change to arrow function

  someFunction2=(something:Observable<string>):Observable<string> =>{
    console.log('someFunction1');
    console.log('constant1 = ', this.constant1); 
    // Cannot read property of constant1
    return of('done');
  }

Upvotes: 0

Related Questions