Managing State in Angular Apps with ngrx/store and ngrx/effects (Part 3)

Netanel Basal
Frontend Weekly
Published in
3 min readMar 3, 2017

Recently I released a new state management pattern. You should check it out.

In this part, we are going to create the todos filters. This will not be like the Redux official todos example because I want to prepare you for the real life.

In real life, you are not going to filter your data locally. Usually, you will get the relevant data from the server that holds the entire data.

I also added two routes:

  1. Home page — HomePageComponent.
  2. Todos page— TodosPageComponent (will replace the AppComponent)

Build the Filters Component

The filters component is just a dumb component that exposes:

  1. filters Input — an array of filters.
  2. active Input — Every time the user navigates to the todos page we want to activate his last choice.
  3. changeFilter Output — emits the selected filter id.

Build the visibilityFilter Reducer

This should be straightforward to you, don’t forget to add the new sub reducer to your store:

Update TodosPageComponent

Previously our smart component was AppComponent now it will be the TodosPageComponent .

The first thing we’ve added is the filters.

The second thing is the changeFilter method that just dispatches the SET_VISIBILITY_FILTER and GET_TODOS actions when the filter changes.

Our goal is always to show the latest value the user has selected.

We only need the filter value once, when Angular creates the component. We can accomplish this with the take operator from Rx.

Take the first emitted value then complete

If you remove the take operator what will happen is the active setter from our filters component will trigger the control setValue method every time you select a filter, but we don’t need this in our case.

Update TodosEffects

When we are dispatching the GET_TODO action, we also need the active filter from our store.

We have access to the store via DI, and we can use the withLatestFrom operator from Rx.

Source one — GET_TODOS stream.
Source two — visibilityFilter stream.

When source one emits, give me also the latest value from source two.

The second argument is a selector function that will give you both values. We are returning just the filter because that’s the only thing we need.

Update TodosService

I just changed the logic to support our new functionally. It just simulates HTTP request with filters.

Remember: This is just one method to complete our goal.

Our final smart component is clean and readable 💪 😎. We are done!

The source code.

Follow me on Medium or Twitter to read more about Angular, Vue and JS!

--

--

Netanel Basal
Frontend Weekly

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.