'Is it OK to use filter() instead of ofType()
In @ngrx/effects we have an operator called ofType. We use this operator in our effects to filter a specific action. For example in the following effect I used this operator to run a request just after login action:
@Effect()
login = this.actions.pipe(
ofType(UserActions.LOGIN_START),
switchMap((action: Action) => {
console.log("login effect")
return this.http.post()
...
})
)
ofType() is from @ngrx/effects. I replaced it with filter() and it seems to work properly. Are the exactly the same?
@Effect()
login = this.actions.pipe(
filter(action => action.type == UserActions.LOGIN_START),
switchMap((action: Action) => {
console.log("login effect")
return this.http.post()
...
})
)
Is anything wrong if I use filter() instead of ofType()?
Solution 1:[1]
Yes and no.
They both work, but the advantage of using ofType is that the action is typed in the rest of the stream.
actions$.pipe(
filter(action => action.type === 'LOGIN_START'),
someMap(action) => {
// action is inferred to Action
})
VS
actions$.pipe(
ofType(logingStart),
someMap(action) => {
// action is inferred to logingStart
})
Solution 2:[2]
I think, it's OK, since the ofType operator uses the RxJS filter operator under the hood, and supports using both string and ActionCreator actions, like the following:
export function ofType(
...allowedTypes: Array<string | ActionCreator<string, Creator>>
): OperatorFunction<Action, Action> {
return filter((action: Action) =>
allowedTypes.some((typeOrActionCreator) => {
if (typeof typeOrActionCreator === 'string') {
// Comparing the string to type
return typeOrActionCreator === action.type;
}
// We are filtering by ActionCreator
return typeOrActionCreator.type === action.type;
})
);
}
https://github.com/ngrx/platform/blob/master/modules/effects/src/actions.ts#L133
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | timdeschryver |
| Solution 2 | Amer |
