Angular 中的管道与订阅

unk*_*ser 12 pipe subscribe rxjs angular

我希望每个人都做得很好。可以请有人清楚地解释一下在管道订阅之间选择哪一个,为什么?当涉及到不仅要获取响应,还要初始化其他一些变量或更改布尔变量时。

还可以看看代码。这是正确的做法吗?

public getAlbums(){
    this.enableLoader = false;
    this.albumHttpService.getAlbums()
        .pipe(
            map((response) => {
                this.enableLoader = false;
                if (!response.albums.length) {
                    this.noDataSet = true;
                    if (response.albums === null) {
                        this.list = [];
                    }
                }
                else{
                    this.noDataSet = false;
                    this.list = response.albums;
                }
            }),
            catchError((error) => {
                this.noDataSet = false;
                this.data = [];
                throw new Error(error);
            }) 
        )
        .subscribe();
}
Run Code Online (Sandbox Code Playgroud)

提前致谢

Adi*_*yaj 21

Pipe基本上获取函数的输出并将其作为另一个函数的输入。这是一种非常出色且有效的数据操作方式,而且功能非常强大。

我们基本上将某些内容的输出传输到不同的函数中,该函数可以修改传入的数据,或者只是在数据之上添加额外的逻辑(触发副作用)。

我们可以在运算符中链接多个逻辑pipe

Subscribe在可观察量上调用以订阅从可观察量推出的最终数据。

简单示例:我有一个发送字符串“World”的可观察对象。

worldObservable$.pipe(
  tap(data=>console.log(data)), // Prints "World"
  map(data=> `Hello ${data}`)
)
.subscribe(data=>console.log(data)); // Prints "Hello World"
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我首先用来tap获取数据,然后记录它。map接下来,我使用更改初始数据的运算符修改数据。当我订阅时,它会记录修改后的数据,而不是初始数据。

我希望它能让你更清楚一些。


Sur*_*yan 11

您可以在其中pipe连接许多其他函数并使用这些函数编写一些逻辑、为视图准备数据等。

subscribe就像最后一点一样,您准备好数据,最好不要在那里编写任何逻辑,只需分配给您的视图模型等。