While working with NgRX 8 my colleagues and me are frequently facing a weird error message when implementing the effects.
Type \'Observable
Actually you need to treat actions created by createAction
as a function and call it to return the action object. Check this desc. So your of(addCommentFailed)
should be of(addCommentFailed())
.
I ran into a similar issue today (same error message) and it was because TypeScript couldn't infer correctly the return type of Array#flatMap. I assume it will be the same for Array#map, RxJS#map or any array that has not been explicitly typed.
Here is the code that crashed :
this.actions$.pipe(
ofType(ActionType),
switchMap((action) => {
return action.cart.flatMap((cartItem: CartItem) => {
if (x) {
return [
ActionCreator1(params1),
ActionCreator2(params2)
];
} else {
return [];
}
}
})
)
So I got the same error message :
Type 'Observable<unknown>' is not assignable to type 'Observable<Action> | ((...args: any[]) => Observable<Action>)'
To fix it, I just had to tell TypeScript that my mapping function returned an array of Action
:
import { Action } from '@ngrx/store';
...
switchMap((action) => {
return action.cart.flatMap((cartItem: CartItem) : Action[] => {
...
Also, typing with Action[]
is safer that with any
!
I struggled with this issue for a while only to find out at the end that VS code automatically imported Observable
from some library instead of rxjs
Hope this saves someone unnecessary head banging.