Search code examples
angularrxjspipesubscribe

Pipe vs Subscribe in Angular


I hope everyone just doing fine. Can, please someone clearly explains which one to choose among pipe and subscribe, and why? when it comes to not only getting the response but also to initialize some other variables or make changes to the boolean variables.

Also have a look at the code. Is it the right way to do it?

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();
}

Thanks in advance


Solution

  • Within pipe you can concatenate many other functions and use these functions to write some logic, prepare the data for the view and etc.

    subscribe is like the last point, where you get ready data and it is better not to write any logic there, just only assignments to your viewmodels or etc.