Javier Manzano
Javier Manzano

Reputation: 4821

How to execute some code after changing state with NGRX?

I'm developing an app with Angular 2.0 and NGRX. I've come from React/Redux, so I'm still figuring out how to do some things.

When I want to print something inside the template I can write something like this:

@Component({
  selector: 'dashboard',
  directives: [MainContainer],
  styleUrls: [
    './dashboard.style.css'
  ],
  template: `
    <main-container [section]="viewSection | async"></main-container>
  `
})
export class Dashboard {

  private viewSection: Observable<MainViewSection>;

  constructor(
    private store: Store<AppState>
  ) {
    this.viewSection = this.store.let(getMainViewSection());
  }

}

But now I want to execute some code after a value changes (it will use store's values as an input (that will change the view afterwards)

I know that I can do it with componentWillReceiveProps in React.

The only thing that I've found that can be usefull is something like this:

export class View {

  constructor(
    private store: Store<AppState>
  ) {
    this.store.select('data').subscribe((val: DataState) => {
      if (!layer) {
        return;
      }
      layer.setData(val);
    });
  }

}

I don't think that's an elegant way, but I cannot figure out another way.. People has told me to use services (I don't know how that fits on this case) and I've read about @Effects, but I don't know if it's what I'm looking for.

Thanks!

Upvotes: 4

Views: 3120

Answers (1)

Filip Lauc
Filip Lauc

Reputation: 3029

I think @Effect is definitely what you are looking for. An @Effect executes when a certain state action gets called. Take this example from the official NgRx example app

  @Effect() clearSearch$ = this.updates$
    .whenAction(BookActions.SEARCH)
    .map<string>(toPayload)
    .filter(query => query === '')
    .mapTo(this.bookActions.searchComplete([]));

Using the whenAction method you specify which action triggers the effect. In this example they use toPayload which returns only the payload of the executed action. But you have access to the entire state of the application.

This is how you could use it for example:

    .whenAction(YourActions.SOMETHING)
    .switchMap(data => this._xhr.send(data.state.yourData) 

Upvotes: 2

Related Questions