1
votes

I have two features, Orders and Items. Inside the orders feature i have a component that dispatch an action.

In a nutshell it looks like this :

constructor(store: Store<OrdersStateContract>) {

    this.orders_subs = store.pipe(select('orders')).subscribe( (orders) => {
      this.orders = orders.orders;
    });

    this.store = store;
}

ngOnInit() : void {
    this.store.dispatch( new LoadOrders({}) );
}

And i realized that when i dispatch the action LoadOrders, it's being caught by the items feature reducer. Is it a common behaviour ? or there's something wrong ?

orders.module.ts :

@NgModule({
  declarations: [
],
imports : [
    MaterialModule,
    BrowserModule,
    StoreModule.forFeature('orders', OrdersReducer),
    EffectsModule.forFeature([OrdersEffects]),
],
providers : [
    OrderService
]
})

items.module.ts :

@NgModule({
  declarations: [
    /*not important*/
  ],
  imports : [
    MaterialModule,
    BrowserModule,
    StoreModule.forFeature('items', ItemsReducer),
    EffectsModule.forFeature([ItemsEffects])
  ]
})

items.reducer.ts

export const ItemsReducer = (state: ItemsStateContract = initialState,
                             action: ItemActions) => {


    switch (action.type) {
        case ItemActionTypes.ItemsFromOrderLoadSuccess:
            return adapter.addAll(action.payload.items, state);

        default:
            return state;

    }
};

orders.reducer.ts

export const OrdersReducer = (state: OrdersStateContract = initialState,
                              action: OrderActions) => {

  switch (action.type) {

    case OrderActionTypes.LoadOrders: {
      return adapter.addAll(action.payload.orders, state);
    }

    default: {
      return state;
    }
  }
};
1

1 Answers

2
votes

TL;DR; It's a normal behavior.

It is as simple as this : Every dispatched action at any level can be catched by any effect and any reducer. (only the effect or reducer can decide to do something with it or ignore it)

In the effects you can use the ofType custom rxjs operator in ngrx. (basically its a filter by action type).

In the reducers you can check the action type and change the state for the actions you want.