【发布时间】:2020-11-21 01:06:41
【问题描述】:
最近我需要使用 RxJS。我试图设计一个错误处理流程,但我发现了一些奇怪的语法传递方法参数:
.subscribe(
x => {
},
console.warn // <- Why does this compile, and warn 'is not 7' in debug console?
);
链接到最小复制:
https://stackblitz.com/edit/rxjs-6-5-error-handle-no-arrow-issue
重现步骤:
- 使用 RxJS 6.5
- 创建一个函数返回 observable
- 订阅 observable
- 将参数传递给订阅
- 只用
,console.warn,不像,error => { console.warn(error); }
如果没有箭头函数,它仍然会将错误传递给 console.warn。为什么?
代码:
import { throwError, concat, of } from "rxjs";
import { map } from "rxjs/operators";
const result = concat(of(7), of(8));
getData(result).subscribe(
x => {
console.log("typeof(x)", typeof(x));
if (typeof(x) === 'string') {
console.log("x Error", x);
return;
}
console.log("no error", x);
},
console.warn // <- Why does this compile, and warn 'is not 7' in debug console?
);
// pretend service method
function getData(result) {
return result.pipe(
map(data => {
if (data !== 7) {
throw "is not 7";
}
return data;
})
);
}
我尝试用谷歌搜索一些关键字,js、rxjs、角度、省略箭头函数、缺少参数……但我找不到这里使用的技术。
谁能提供解释此机制的链接?
以下两个问题相关但不解释行为,只说“等价”:
线
地图(this.extractTreeData)
相当于
map(tree => this.extractTreeData(tree))
【问题讨论】:
-
函数是javascript中的“第一类对象”。它们是被声明为“内联”还是通过变量引用并不重要
-
console.warn是一个函数,它期望一个函数,所以很高兴 -
感谢大家在我提问时留言,让我弄清楚,我来自Java 8,尤其是“函数是一流的对象”是我所需要的
标签: javascript angular rxjs operator-keyword