【问题标题】:Not able to access variable outside of second function in reactive programming在反应式编程中无法访问第二个函数之外的变量
【发布时间】:2019-10-09 16:20:06
【问题描述】:

我有 2 个 Javascript 函数。第一个将值返回给第二个。在第二个函数中,我无法访问之前声明的常量。

我尝试重命名常量。

//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');
  }

}

我希望输出是“constant1”。但我收到“无法读取常量 1 的属性”的错误。

【问题讨论】:

标签: typescript rxjs nestjs


【解决方案1】:

这是因为 this 没有绑定到 AppService 因为它的调用:

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

而是将someFunction2 作为箭头函数传递,其中this 是词法绑定的,这意味着无论this 用于箭头函数的调用者,它在箭头函数中都是相同的:

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

【讨论】:

    【解决方案2】:

    尝试更改箭头功能

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

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 2022-06-13
      • 2021-01-15
      • 2021-12-24
      • 1970-01-01
      相关资源
      最近更新 更多