首先你需要了解你实际传递给的是什么.subscribe
功能。本质上它接受三个可选参数next
, error
and complete
。其中每个都是当源可观察对象发出相应通知时要执行的回调。
因此,当您使用箭头函数时,您可以定义一个就地回调函数。
sourceObservable.subscribe({
next: (value) => { },
error: (error) => { },
complete: () => { }
});
相反,您可以单独定义函数并将其用作回调。
onNext(value) {
}
onError(error) {
}
onComplete() {
}
sourceObservable.subscribe({
next: this.onNext,
error: this.onError,
complete: this.onComplete
});
现在这就是你所看到的。但是您传递的不是用户定义的函数,而是内置函数console.warn()
功能。反过来,通知中的值将作为参数传递给回调函数。所以你的错误的价值is not 7
作为参数发送给console.warn()
然后它会完成它的工作(即打印到控制台)。
然而有一个问题。如果您想使用任何类成员变量this
回调中的关键字,它会抛出一个错误,指出该变量未定义。那是因为this
指回调中函数的范围,而不是类。克服这个问题的一种方法是使用箭头函数(我们已经看到了)。或者使用bind() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind函数绑定的含义this
类的关键字。
sourceObservable.subscribe({
next: this.onNext.bind(this),
error: this.onError.bind(this),
complete: this.onComplete.bind(this)
});
因此,如果您只想拥有错误回调,您可以明确声明它并忽略其他回调。
sourceObservable.subscribe({ error: console.warn });
现在关于你的问题“为什么函数调用中没有括号”, 讨论了here https://stackoverflow.com/a/15886327/6513921 and here https://stackoverflow.com/a/19732998/6513921。参数需要对函数的引用,函数名称表示它们的引用。