0

这就是我想要做的,我将一个函数引用从 Provider1(存在于 module1)传递给 Provider2(存在于 module2)。当我尝试调用该函数时,“this”的值未定义。关于可能出了什么问题的任何想法?

模块1.ts

@Module({
  controllers: [Controller1],
  providers: [Provider1],
})
export class Module1{}

Provider1.ts

@Injectable()
export class Provider1 {
  constructor(private readonly provider2: Provider2) {} 
  providerFunction() {
    this.provider2.provider2Function(new HelperClass().helperFunction);
  }
}

助手类.ts

@Injectable()
export class HelperClass {
  helperFunction() {
    return this.someValue; //Here, this is undefined
  }
}

Provider2.ts

@Injectable()
export class Provider2 {
  provider2Function(helperFunction: ()=>void) {
    console.log(helperFunction());
  }
}
4

1 回答 1

0

这是因为this以这种方式传递方法时会发生变化。试试这样:

@Injectable()
export class Provider1 {
  constructor(private readonly provider2: Provider2) {} 
  providerFunction() {
    const helper = new HelperClass();
    this.provider2.provider2Function(helper.helperFunction.bind(helper));
  }
}

this更多关于关键字如何在这里工作。

于 2020-07-20T06:28:52.370 回答