我正在尝试测试组件上存在的Subject symbol$的输出。具体来说,主题符号$应该发出(这是正确的词吗?)一个值,每当组件属性symbol发生更改时。
但是,直到我看到一个在线代码块使用.subscribe(next() {. })而不是.subscribe((x) => {.});语法,我才能找到测试输出到.subscribe的方法。
这两个电话有什么区别?为什么其中只有一个起作用?
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']);
});发布于 2021-07-13 18:57:52
将箭头函数与普通函数传递到订阅中是有区别的,特别是围绕这一点。
具有Arrow功能的观察员:

具有职能声明的观察员:

但要小心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`)}
});因为this的作用域是函数,所以next(apple)函数中的this不会引用任何类级变量,而是假设您正在定义一个新变量,该变量位于next(apple)函数的局部变量中。
箭头函数的情况并非如此。箭头函数中的this的作用域为类级变量。
https://stackoverflow.com/questions/68355418
复制相似问题