“next”在 .subscribe() 中做什么?

the*_*ack 4 subscribe observable rxjs angular

我已经看到了三种通过可观察/调用 API 来“侦听”值更改以从后端获取数据的方法。

其中一种方法有“next:”:

this.MySubscription = this.myService.getStuff().subscribe({
    next: (data) => {
        <insert code to perform operations with "data">
    }, error: (err) => {
        console.error(err);
        // <insert code for what to do on failure>
    }
});
Run Code Online (Sandbox Code Playgroud)

在 Angular 网站https://angular.io/guide/observables上我看到了这一点,其中包含“next(”:

// Call subscribe() to start listening for updates.
const locationsSubscription = locations.subscribe({
    next(position) {
        console.log('Current Position: ', position);
    },
    error(msg) {
        console.log('Error Getting Location: ', msg);
    }
});
Run Code Online (Sandbox Code Playgroud)

但我一直只是以“正常方式”这样做,就像这样(没有“下一步”):

this.MySubscription = this.myService.getStuff().subscribe((data: any) => {
    <insert code to perform operations with "data">
}, error => {
    console.error(error);
    <insert code for what to do on failure>
});
Run Code Online (Sandbox Code Playgroud)

这三种订阅方式在功能上有什么区别吗?每种方法如何产生不同的结果?

kag*_*ole 8

你在问题中展示的三种方式做同样的事情。
这只是给观察者提供 3 种不同的方式。

  • 在第一个中,您给出一个PartialObserver<T>带有函数的对象next,该函数将在收到不是错误的值时执行
  • 在第二个中,您再次给出一个PartialObserver<T>带有函数的对象next,但是使用简写函数语法
  • 在第三个中,您使用的Observable.subscribe(<closure>)基本上是一个快捷方式Observable.subscribe({ next: <closure> })

你总是使用第三种方式,除非你必须处理error和/或complete情况。
如果您确实必须处理这些情况,则必须在问题中显示的第一种或第二种方式之间进行选择;任何一种都有效,只需保持代码的一致性(在代码中始终使用相同的方式;使用 linter)。

供参考: https: //rxjs.dev/api/index/class/Observable#subscribe

  • 是的,您可以通过提供第二个闭包作为第二个参数,但它已被弃用(请参阅参考链接)。我的意思是“当接收到一个不是错误的值时将被执行(将在‘error’闭包中处理)”。所有“next”闭包只会在无错误时执行;错误由“error”闭包处理。查看 [`Observer` 指南](https://rxjs.dev/guide/observer)。 (2认同)