.subscribe(x=> ...) 和 .subscribe(next(...)) 的区别?

Joe*_*Lau 5 rxjs angular

我正在尝试测试symbol$组件上存在的主题的输出。具体来说,只要组件属性symbol发生变化,Subject symbol$ 就应该发出(这里是正确的词吗?)一个值。

但是,symbol$直到我在网上遇到一大块使用 .subscribe(next() { ... }) 而不是 .subscribe((x) => {.. .}); 句法。

2个电话有什么区别?为什么其中只有 1 个有效?

it('should fetch data', () => {
  const actuals: string[] = [];

  // commented version doesn't work
  // component.symbol$.subscribe((symbol) => { actuals.push(symbol); } ;

  component.symbol$.subscribe({
    next(symbol) {
      actuals.push(symbol);
    },
  });

  expect(actuals).toEqual(['']);
  component.symbol = 'IBM';
  component.ngOnChanges();

  expect(actuals).toEqual(['', 'IBM']);
});
Run Code Online (Sandbox Code Playgroud)

Deb*_*ahK 5

将箭头函数与普通函数传递到订阅中存在差异,特别是围绕this

具有箭头函数的观察者: 在此输入图像描述

带有函数声明的观察者: 在此输入图像描述

但要注意this

const sub = source$.subscribe({
  next(apple) { this.apple = apple }, // Does NOT reference the 
                                      // class-level variable
  error(err) { console.log(`Error occurred: ${err}`)},
  complete() { console.log(`No more apples, go home`)}
});
Run Code Online (Sandbox Code Playgroud)

由于this作用域为函数,因此函数thisnext(apple)不会引用任何类级变量,但会假设您正在定义next(apple)函数本地的新变量。

箭头函数的情况并非如此。this箭头函数内的作用域为类级变量。