Angular

Angular and RxJS Patterns — Use Reactive Programming to Compose and Manage Data in Angular Apps

A guide to building composable data streams, fetching data, handling user interaction, and caching API responses using RxJS

Photo by Lexi Ruskell on Unsplash

In Angular applications, we use reactive programming frequently, and we are able to develop apps without needing global state management libraries. The following techniques can be extended for general real-world use cases:

In this article, I will show how to use RxJS to handle the following cases:

Fetch data Compose data Handle user interaction Cache data from API requests

I will use a dummy API from https://jsonplaceholder.typicode.com for this article.

For more content like this, check out https://betterfullstack.com

Fetch Data

There are many ways to fetch data in Angular, but the following are the most common methods:

Create a business service and then inject it into an Angular Container Component and subscribe it to fetch data. Then assign that data to a local variable. Call a service on a Resolver or dispatch an ACTION in an Angular Container Component lifecycle ngOnInit and map the data from the global state to the UI by using raw data or observable data.

In this part, I will introduce another way to fetch data from a server without using subscribe or state management.

First, I create a simple service.

UsersService to get list of user

There are 3 points to remember from this service:

We can define a URL in one file and import it to this service. We can manually control the import to each module or just put providedIn: 'root' to set it globally. We can use pipe to transform data from here.

Now inject the service to the container component

Use UsersService on AppComponent

Do you see the weird thing happing on AppComponent ? It is changeDetection: ChangeDetectionStrategy.OnPush .

What is this?

The change-detection strategy to use for this component. When a component is instantiated, Angular creates a change detector, which is responsible for propagating the component’s bindings.

We have 2 types:

ChangeDetectionStrategy#OnPush sets the strategy to CheckOnce (on demand).

sets the strategy to (on demand). ChangeDetectionStrategy#Default sets the strategy to CheckAlways .

We use OnPush because it improves performance by minimizing change detection cycles.

With OnPush , the component is only checked for changes when:

The @Input property changes. An event is emitted An Observable emits

Finally we use async pipe in the template:

AppComponent Template

Note that async pipe is very powerful because it will automatically remove subscriptions when the component is destroyed.

Compose data

This concept is weird to those who are beginners with reactive programming. You can think of this as being similar composing higher-order components in React or compose in functional programming.

I will compose two streams together to get data. So from /users I have basic user information and from /posts I can get all the posts. Then based on the userId I can determine the author’s posts.

I will create one response with user information with the posts property that contains all the posts that belong to that specific user.

I create a PostsService .

PostsService to get Post data

Next I inject this service to UsersService .

Inject PostsService into UsersService

You can see from the code above, I use combineLatest to combine user$ and post$ from PostsService together. Then I use pipe and map to merge data from two streams into one.

So, I will have user information plus a posts property.

Finally, I add it to the AppComponent .

add userWithPost$ to AppComponent

Handle user interaction

In this section, I will show how to handle user interaction simply by using RxJS in Angular.

Here are the steps:

Create an action stream. Combine actions and data streams. Emit a value every single time an action occurs.

add action stream to UsersService

You can use Subject or BehaviorSubject to create an action stream. In the code sample, I use Subject to create userSelectedAction and set it to private .

Then I combine the action stream and data stream together by combineLatest which is selectedUser$ .

Lastly, I create a method named changedSelectedUser(id) to emit the new user ID every time that action occurs.

You can see the new change on AppComponent now:

new update for AppComponent

Here is a demo:

Demonstration handle user click by rxjs

Cache Data from API Requests

In this section, I will demonstrate a simple way to cache data from an API.

Here is a pattern that I have seen many developers use to cache data.

store data in public variable

This has a problem that we will lose in the stream.

How I prefer to use shareReplay() :

use shareReplay to do caching

There are 3 reasons why I use shareReplay :

It shares an observable with all subscribers. It replays the specified number of entries upon subscription. It remains active even if there are no current subscribers.

Note that you generally want to use shareReplay when you have side-effects or expensive computations that you do not wish to be executed amongst multiple subscribers.

Summary

To sum it up, in Angular we can apply RxJS to do practically everything, and these reactive programming techniques can make your app simpler.

We can fetch data without subscribe , make composable streams, create an effective way to handle user action, and cache our API response data seamlessly.

We also learned that we can use OnPush to boost the performance of the application.

I hope you found this article useful! You can follow me on Medium. I am also on Twitter. Feel free to leave any questions in the comments below. I’ll be glad to help out!

Check the source code sample here: