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

时间:2016-08-09 14:21:06

标签: rxjs rxjs5 angular2-observables

我有这样的订阅:



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




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

我想将上下文绑定到subscribe函数但我从未见过。 是否可以不做像

这样的事情



that = this




1 个答案:

答案 0 :(得分:5)

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

当你写:

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(和编程语言)概念。