NGRX: TypeError: Actions must have a type property

NGRX: TypeError: Actions must have a type property

我是 ngrx 的新手,我遇到了一个例外,不知道为什么...

我正在尝试 dispatch 一个 action 并在 effect 中处理它,但我不断收到错误消息:TypeError: Actions must have a type property

操作:

export const TEST_ACTION = 'test_action';
export class TryTest implements Action {
    readonly type = TEST_ACTION;

    constructor(public playload: any) {
    }
}
export type MyActions = TryTest;

效果:

import * as MyActions from "./myactions.actions";

@Injectable()
export class MyEffects {
    @Effect()
    testEffect = this.actions$
        .ofType(MyActions.TEST_ACTION)
        .map((action: MyActions.TryTest) => {
            return 'something'
        });

    constructor(private actions$: Actions) {}
}

组件:

this.store.dispatch(new MyActions.TryTest({ name: 'test' }));

我正在使用:

效果:4.0.5 和商店:4.0.3

如果这有助于其他人开始...原来我没有返回 ngrx 在地图运算符中期望的操作。

因为效果必须 return 最后一个动作。 所以你有两个选择:

  1. return 一个{类型:字符串}对象
  2. return一个新的Action()

    import * as MyActions from "./myactions.actions";
    
    @Injectable()
    export class MyEffects {
        @Effect()
        testEffect = this.actions$
            .ofType(MyActions.TEST_ACTION)
            .map((action: MyActions.TryTest) => {
                return {type:'your_action'}
            });
    
        constructor(private actions$: Actions) {}
    }
    

默认情况下,您创建的所有效果都应该发出一个被分派到商店的动作。 因此,作为效果函数的结果,您需要 return 类型 Observable<Action> 其中 Action 是来自 @ngrx/store:

的接口
export interface Action {
    type: string;
}

所以用 属性 type 映射到对象将起作用:

 @Effect() testEffect = this.actions$
             .ofType(MyActions.TEST_ACTION)
             .map((action: MyActions.TryTest) => {
                    return {type:'action_for_test_effect'}
              });

在这种情况下,您应该在减速器中支持 action_for_test_effect

如果您不需要从 effect 派发任何 action,您可以通过添加配置对象到 effect 来禁用它:

@Effect({dispatch: false}) testEffect = this.actions$
                 .ofType(MyActions.TEST_ACTION);