2

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.'

edmond tm
  • 59
  • 2
  • 6

2 Answers2

1

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);
}
Kim Kern
  • 54,283
  • 17
  • 197
  • 195
0

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');
  }
Fan Cheung
  • 10,745
  • 3
  • 17
  • 39