gpt4 book ai didi

rxjs - 如何为 rxjs 订阅回调函数设置上下文?

转载 作者:行者123 更新时间:2023-12-04 22:43:14 26 4
gpt4 key购买 nike

我有这样的订阅:

this.test.subscribe(params => { 
...some code
});


如果我传递回调函数而不是箭头函数,则缺少上下文。

我想将上下文绑定(bind)到订阅函数,但我从来没有看到过。
有没有可能不做类似的事情

that = this

最佳答案

我会尝试回答,但我仍然不太确定你的意思。

当你写:

const v = 42;
observable.subscribe(x => {
// here you have access to `v`
});

但是当你写:
{
const v = 42;
observable.subscribe(f);
}

function f(x) {
// here you do not have access to `v`
}

这就是它应该的样子。如果你想要 f要查看不在其声明范围内的变量,则必须将它们设为参数并适本地传递它们。例如:
{
const v = 42;
observable.subscribe(x => f(x, v));
}

function f(x, v) {
// here you **do** have access to `v`
}

或者,如果您可以在要捕获的变量的上下文中定义回调:
{
const v = 42;
observable.subscribe(x => f(x));
function f(x) {
// here you **do** have access to `v` because it is in scope
}
}

这回答了你的问题了吗?但它与 RxJS 无关,它们是纯 JavaScript(和编程语言)概念。

关于rxjs - 如何为 rxjs 订阅回调函数设置上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38853380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com