将私有方法传递给 lambda 时,typescript 字段为 null
typescript field is null when passing a private method to a lambda
我有以下class;我尽可能简短地解释了这个问题:
@Injectable()
export class TestService {
...
private testSubscription: Subscription = new Subscription;
constructor(
private store: Store<FromTest.IState>,
private otherService: otherService) {
}
public MainTestMethod() {
this.testSubscription = this.otherService.getSomethingObservable().subscribe(toBeCalledTestMethod)
}
private toBeCalledTestMethod(something: boolean) {
this.store <- undefined
}
...
}
当传递订阅方法时,字段 "store" 未定义。
但是,当我将订阅方法更改为:
this.testSubscription = this.otherService.getSomethingObservable().subscribe(x => toBeCalledTestMethod(x))
字段 "store" 有一个值(这是预期的)。
很高兴我找到了让它工作的方法,但我不明白为什么将方法作为 lambda 传递会导致不同的行为。
我是 typescript 的新手,angular 所以想了解原因。
提前致谢!
感谢@ritaj 的评论 "toBeCalledTestMethod.bind(this)" 我现在知道为什么了。
传递这样的方法:
this.otherService.getSomethingObservable().subscribe(toBeCalledTestMethod)
将没有上下文的方法传递给订阅函数。
要使用该方法保留上下文,您可以使用 bind 将其绑定到 class 或使用 lambda 来保留您的上下文。
因为传递 lambda 将传递一个函数,该函数将在其上下文中执行该方法。
我有以下class;我尽可能简短地解释了这个问题:
@Injectable()
export class TestService {
...
private testSubscription: Subscription = new Subscription;
constructor(
private store: Store<FromTest.IState>,
private otherService: otherService) {
}
public MainTestMethod() {
this.testSubscription = this.otherService.getSomethingObservable().subscribe(toBeCalledTestMethod)
}
private toBeCalledTestMethod(something: boolean) {
this.store <- undefined
}
...
}
当传递订阅方法时,字段 "store" 未定义。 但是,当我将订阅方法更改为:
this.testSubscription = this.otherService.getSomethingObservable().subscribe(x => toBeCalledTestMethod(x))
字段 "store" 有一个值(这是预期的)。
很高兴我找到了让它工作的方法,但我不明白为什么将方法作为 lambda 传递会导致不同的行为。
我是 typescript 的新手,angular 所以想了解原因。
提前致谢!
感谢@ritaj 的评论 "toBeCalledTestMethod.bind(this)" 我现在知道为什么了。
传递这样的方法:
this.otherService.getSomethingObservable().subscribe(toBeCalledTestMethod)
将没有上下文的方法传递给订阅函数。
要使用该方法保留上下文,您可以使用 bind 将其绑定到 class 或使用 lambda 来保留您的上下文。
因为传递 lambda 将传递一个函数,该函数将在其上下文中执行该方法。