Better ways to share data between components.

Sharing data in the Angular application

When it comes to sharing data between components in an Angular application we have to remember that there more than one right way to do it!

Let’s go over some assumptions, rules, and considerations for this article.

Consider: Follow a container presenter pattern. Check out my video on this here.

Your components have as little responsibility as possible; whether it is to get data from the server or just display it.

You create dumb components whenever possible.

You keep your dependency injections in the components to a minimum.

You abstract business logic to the services.

Assumptions: You don’t always have the luxury of adding a state management library to your application.

I used NGRX and I know that it is a complex library and if the whole team is not on board to use it, then your code becomes a mish-mash of different approaches.

Get the whole team to commit to a state management library or go with another approach like the one described here.

Rules: Keep application performance at the top of the priority list.

Your code has to be clean and easy to read and maintain.

Say No to bubbling up events.

Here is an example of 3 components that all produce data. They have no access to the data they create. Events bubble up to the app.component.

I want to show you what NOT to do!

checkout StackBlitz:

https://stackblitz.com/github/katesky/messages-sent-app

Next up is code where we will add a service that will manage our data and it will be shared with all of our components.

Use service with a subject

git checkout with-service or go to code here –> new branch

We will create a service that will hold a list of our data in a private BehaviorSubject of type an array of strings.

We will add a public observable of that BehaviorSubject to our service.

Now we can add a function that will mutate our data.

We now have a central area where our data is held.

It can be shared across all of our components and there are no events that have to be emitted up to the parents’ components.

Now that our application is truly reactive we can change out changeDetection to OnPush. More info on it here.

Change template to using async pipe. Read about it here!

We can use data$ in all other components the same way as here:

Checkout Stackblitz with code complete:

https://stackblitz.com/github/katesky/messages-sent-app/tree/with-service

I hope this article was usefull for you.

I was able to show you something new and you will avoid some of the mistakes I made when I got started with Angular.

One of my passions is to be able to inspire mothers to get started in technology sector. I am a programmer with over 20 years of experance in IT.

I am also a mother of 5 children. I hope one day my daughters will be inspired by my story to go into STEM.

Till next time!

Kate Sky.