How I work with Observables in Angular

Introduction

This is a subject that is intimidating for a lot of folks out there and I have heard people explain it’s just too hard. In the beginning when I first started learning Angular I was having the same feelings. Like… What the hell? …


This content originally appeared on DEV Community and was authored by Dimitar Stoev

Introduction

This is a subject that is intimidating for a lot of folks out there and I have heard people explain it’s just too hard. In the beginning when I first started learning Angular I was having the same feelings. Like… What the hell? Why do I even need this Observable thing?

I managed to love it now and I prefer to always go reactive and always consider using RxJS as my goto approach first.

But with great powers, you know the rest.

There are many ways to deal with a single problem and this approach is my preferable one.

In the next lines I am going to talk about how I like to work with Observables and how I prefer to handle data.

This is part of my Angular series and it would be great if you subscribe / follow. It shows me that these articles are actually helpful to someone.

What to expect?

  • Observables and declaring them
  • Subscribing to them with Async pipe
  • Working on data with Pipes
  • Combining pipes in the HTML template
  • Working demo showing all of the above

What are Observables?

An observable. Simply put - a producer of data, a pipe that is delivering information on a consumer. It produces the value and delivers it when asked to.

There are certain types of Observables. We have cold ones and hot ones. Streaming data when asked and streaming data regardless of potential subscribers respectfully.

The observable itself plays a very central part of the reactive programming that is used in the framework. It is used often to manage asynchronous data, HTTP requests for example, inputs, and custom logic.

The “Observable” interface that the class implements, defines a set of methods and properties that allow us to interact with the observable, subscribe to the emissions and handle any errors. It includes a completion event as well.

When we subscribe to an observable, it creates a new subscription object. This object is used to control and manage the interaction between the observable and the subscriber.

It is important to point out that unsubscribing is an important part of the working flow of working with Observables. Especially if we are talking about hot observables that are sending data regarding the user interaction.

The “async” pipe is doing this for now and it is my preferred way to deal with Observables.

Another thing that RxJS is providing us with is the ability to manipulate the data before passing it to the consumer. We have various operators to choose from that have different behaviors.

Using Async pipe

When it comes to my personal preferences I usually prefer to define the Observable in my class and use the async pipe in the template.
This is great, since it automatically does subscribing and unsubscribing to it. Getting the data is easy and handling it is easy as well.

Let’s get to the examples. We have a list of users and we want to iterate over it. Our task is to list the information to our user.
You can check the entire source code in the repo, but I am going to provide snippets here.

I usually create the services, the interfaces and then declare the observable with the correct type in the .ts file. Subscribing is done with the async pipe.
In this example I am getting the entire list of users.

observable declaration

observable template

Angular is using the pipe and subscribes to this observable under the hood. The data is loaded and when delivered - rendered.

We are going to implement routing and loading single data usage. RxJS is going to help us here.

Loading single user

The moment a user is clicked in the list we are using routerLink to change the route and load the data of the specific user. We will load status and description. Nothing more for our little demo, but I am going to highlight my approach on controlling the data there.

I am using from operator here to convert my USERS array to an observable stream and ‘find’ to return either the found user or an error using the throwError

observable single user

Many ways to handle the id of the route, but I am going to use something simple for this. I want to showcase the template and the combination with the *ngIf directive.

I am still using the onPush change detection and the user is an observable of User type. The control of the data is reactive.

single user template

Let’s say I want to list the active users. We have a property that sets their “status”. I would go with the following - since I already have the users, I could just pipe them again and filter it there.

Fast and clean!

filter users

In the provided repo below, you can check a functionality that adds users, update the UI automatically on update using BehaviorSubject and Observable.

The template is rendered with an async pipe as well.

filter users template

How to use Observables and Pipes together in Angular?

I love pipes. I try to use them as much as possible. I know not every time is the best time to use them and sometimes it’s just not the case.

But let’s say you have a response and get that users. But you need to arrange the data in specific order.

What do you do?
I could do the job perfectly with a custom Pipe here. I get Users[] and return Users[].

Let’s see an example.

I am reworking the template in order to handle null users. Chaining pipes is just too great!

observable with pipe

One thing I usually do as well is combine all these Observables into one. I am using combineLatest in this example to use it as a single variable in the template.

combine latest

The template:

combine latest template

Demo project

The entire source code is in a repo on my GitHub profile. Every example here is there and you can check the interactions and the way it is structured.

Here is the link

GitHub repository

I am planning to expand this into a bigger demonstration project with design, functionality and some patterns and practices, so if you are interested in that - follow and “star” the project.

Thank you in advance!

Conclusion

I really love working with Observables, Subjects, BehaviourSubjects and pipes. When I start a feature, I always try to plan in advance and I try to plan as reactively and declaratively as possible.

In the project I listed above, I am planning to create a full application with best practices and every article I write for Angular is going to be referred to and implemented in the project ( whenever is possible of course ).

Thank you and good luck!


This content originally appeared on DEV Community and was authored by Dimitar Stoev


Print Share Comment Cite Upload Translate Updates
APA

Dimitar Stoev | Sciencx (2023-04-15T13:15:31+00:00) How I work with Observables in Angular. Retrieved from https://www.scien.cx/2023/04/15/how-i-work-with-observables-in-angular/

MLA
" » How I work with Observables in Angular." Dimitar Stoev | Sciencx - Saturday April 15, 2023, https://www.scien.cx/2023/04/15/how-i-work-with-observables-in-angular/
HARVARD
Dimitar Stoev | Sciencx Saturday April 15, 2023 » How I work with Observables in Angular., viewed ,<https://www.scien.cx/2023/04/15/how-i-work-with-observables-in-angular/>
VANCOUVER
Dimitar Stoev | Sciencx - » How I work with Observables in Angular. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/04/15/how-i-work-with-observables-in-angular/
CHICAGO
" » How I work with Observables in Angular." Dimitar Stoev | Sciencx - Accessed . https://www.scien.cx/2023/04/15/how-i-work-with-observables-in-angular/
IEEE
" » How I work with Observables in Angular." Dimitar Stoev | Sciencx [Online]. Available: https://www.scien.cx/2023/04/15/how-i-work-with-observables-in-angular/. [Accessed: ]
rf:citation
» How I work with Observables in Angular | Dimitar Stoev | Sciencx | https://www.scien.cx/2023/04/15/how-i-work-with-observables-in-angular/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.