ngrx ofType, @ngrx/effects

Viewed 13877

i try to understand how typeof effects work under the hood in ngrx, if i declare in my app module:

....

@NgModule({
    imports: [
        EffectsModule.forRoot([TodosEffectsService])
],

....

and i write effect file sure:

@Effect() createTodos$ = this.actions$
.ofType(CREATE_TASK)
    .map(() => {
        console.log('called');
            return { type: 'OTHER'};
});

@Effect() addTodos$ = this.actions$
.ofType(CREATE_TASK)
    .map(() => {
        console.log('called');
            return { type: 'OTHER'};
});

i try to understand, now in run time i dispatch a action this.action$ is subscribed and every time execute ofType to match the type? or ofType once execute!?

if it called once, when i dispatch action how effects know every time witch effect to subscribe/execute?

thank all!

4 Answers

this.actions$ .ofType(CREATE_TASK) will call every time when your action get dispatched, after your reducer case get execute. like Redcucer

switch(action) {
case youractionsname.CREATE_TASK : {
// pure function logic here
   }
}

First reducer will execute and then it will look into effect, if you have any effect who has type of 'CREATE_TASK'. In subscription pattern whatever you have subscribe that will be call back function and it will store in array under the hood based on condition. When you dispatch action based on condition that all function will call who meet the condition.

The point is that the ofType is not exported in Actions class inside the ngrx/effects so you can use it like following: 1- import ofType from ngrx/effects which would be

import { Injectable } from "@angular/core";

import { Effect, Actions, ofType } from "@ngrx/effects";
import * as omid from "@ngrx/effects";
import { of } from "rxjs";
import { map, switchMap, catchError } from "rxjs/operators";
@Injectable()
export class PizzasEffects {
  constructor(
    private actions$: Actions,
    private pizzaService: frtomServices.PizzasService
  ) {}

  @Effect()
  LoadPizzas$ = this.actions$.pipe(
    ofType(pizzaActions.LOAD_PIZZAS),
    switchMap(() => {
      return this.pizzaService.getPizzas().pipe(
        map(pizzas => new pizzaActions.LoadPizzasSuccess(pizzas)),
        catchError(error => of(new pizzaActions.LoadPizzasFail(error)))
      );
    })
  );
}
Related