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)
?