10 Sep 2020
1 min

NGRX | Use effects and router-store to isolate route related side effects.

One of the major advantages of ngrx is that we can isolate side effects from the components.

When we need to have router related data on the component we'll usually use the ActivatedRoute service from the component itself. For example, we can get the id from a route using this technique:

export class MyComponent {
  id: string;
  id$ = this.activatedRoute.params.pipe(
    map(params => params.id),
    tap(id => this.id = id),
  );
}

Let's isolate this using @ngrx/effects. The first goal is to get the route param from the URL.

How not to do it

We might be tempted to try using the ActivatedRoute service on the effects, but it's useless. It's only accessible on the "associated with a component loaded in an outlet", quoted [from here](https://angular.io/api/router/ActivatedRoute).

Another thing we might think of is to use the Router service. But again, we won't have the url parameter accessible in a clear, easy to use way.

What we can do, is to use selectRouteParam state selector from @ngrx/router-store.

Let's dive into the example. (stackblitz link at the bottom of the article)

How it's done right

Setting up the effect:

  setCurrentCourse$ = createEffect(() => this.store$.pipe(
    select(selectRouteParam('id')))
      .pipe(
        map((id: string) => setIds({id})), // dispatch a new action to set the selected id
      ),
    {dispatch: true},
  );

Then our component can be as simple as:

import { Store, select } from '@ngrx/store';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `{{selectedId$ | async | json}}`,
})
export class HomeComponent {
  selectedId$ = this.store.pipe(select((state: any) => state.featureName.selectedId));
  constructor(
    private store: Store,
  ) { }
}

The takeaways

That a basic example showing just how to get a param. The real power comes when we need to use that param and fetch some data with it. Then we'll have an effect where we'll use the switchMap operator to fetch the data using this id from the URL. On the component, we'll just subscribe to the fetched data, and that's it.

If you liked it, please show me some love here or on my twitter @adamgenshaft.

Frequently asked questions

How do I get a route parameter inside an NgRx effect?

Use the selectRouteParam() selector from @ngrx/router-store with store.pipe(select(selectRouteParam('id'))) inside a createEffect(), then map the value to an action such as setIds({id}). Because the selector reads router state, the id reaches the store without the component touching ActivatedRoute. Pass {dispatch: true} so the mapped action is dispatched.

Can I use ActivatedRoute inside an NgRx effect?

No, ActivatedRoute is only accessible for a component loaded in a router outlet, so an effect, which is not a component, cannot rely on it. Instead, use the selectRouteParam() selector from @ngrx/router-store, which exposes the current route parameter through the store and keeps effects isolated from components.

How do I fetch data using a route id in an NgRx effect?

Chain switchMap after the route parameter selector in your effect, calling your data service with the id and mapping the result to a success action. switchMap cancels the previous inner request when a new id arrives, so only the latest route's data is dispatched. The component then just subscribes to the fetched data from the store instead of calling the service itself.

How do I read a route parameter stored by NgRx in a component?

Select the value from the store in the component with store.pipe(select(...)), once an effect has dispatched the id into state. The component then stays free of router logic: it never injects ActivatedRoute and only reads the feature state, such as state.featureName.selectedId. For production code, prefer a typed selector created with createSelector() over an inline (state: any) function.

Share this post

Sign up for our newsletter

Stay up-to-date with the trends and be a part of a thriving community.