7

I have inherited some angular code using ngRX framework

Actions are defined like:

import {Action} from "@ngrx/store";

export const MY_ACTION: string = 'MY_ACTION';

export class MyAction implements Action {
    readonly type = MY_ACTION;

    constructor(public payload?:any) {
    }
}

Dispatched like:

store.dispatch(new MyAction());

Reduced like:

export function storeReducer(state: any, action:Action): ApplicationState {
    console.log("*** " + action.type);

    switch(action.type) {
        case MY_ACTION:
            return handleMyAction(state, action);
        }
    }
}

function handleMyAction(state: ApplicationState, action: MyAction): ApplicationState {
    const newState: ApplicationState = _.cloneDeep(state);
    // change newState as required
    return newState;
}

and subscribed to like:

  @Effect() doSomethingWithMyAction$: Observable<Action> = this.actions$
        .pipe(
            ofType(MY_ACTION))
        .switchMap(action =>
            // Do something
        );

Now I'm probably showing my ignorance of JS here (coming from a .net background) but why does an action have a type (set to a const string)? Couldn't you use something like typeOf to check what type of action it is?

e.g.

export class MyAction implements Action {
    constructor(public payload?:any) {
    }
}

switch(typeof(action)) {
    case MyAction: // or typeOf(MyAction)
        return handleMyAction(state, action);
    }
}


@Effect() doSomethingWithMyAction$: Observable<Action> = this.actions$
      .pipe(
          ofType(MyAction))
      .switchMap(action =>
          // Do something
      );

Then you could get rid of the type consts and have simpler code.

The fact it's not done this way leads me to assume it can't be done this way, or there are very good reasons not to do it this way, so I assume it's my lack of knowledge around js/typescript coming in to play.

In typescript does typeOf give you the to the class, or just 'object' or similar?

Is there an js/ts equivenent of c#'s if(action is MyAction)?

mattumotu
  • 1,436
  • 2
  • 14
  • 35
  • 1
    This isn't answering your question, but if you're inheriting the codebase and starting new developments on it, I'd recommend taking the time to upgrade to NgRx 8.x. It's way cleaner, way less boilerplate, and the effects are typed. – xandermonkey Oct 04 '19 at 13:08
  • 1
    https://medium.com/ngrx/announcing-ngrx-version-8-ngrx-data-create-functions-runtime-checks-and-mock-selectors-a44fac112627 – xandermonkey Oct 04 '19 at 13:08
  • 1
    @xandermonkey thanks that's really helpful, I think the 'new way' kinda negates my question – mattumotu Oct 07 '19 at 07:23

0 Answers0