NgRx报错‘Actions must have a type property’,Effects类问题求助
解决NgRx Effects中'Actions must have a type property'错误
我看了你写的TripsEffects类和遇到的错误,这个问题挺常见的,大概率是你的LoadTripsSuccess action定义不符合NgRx的要求,下面一步步帮你排查解决:
一、错误核心原因
NgRx要求所有action必须实现Action接口,并且必须包含一个只读的type属性(用来唯一标识action类型)。你代码里的new LoadTripsSuccess(user)抛出这个错误,基本是因为LoadTripsSuccess类没有正确设置type属性。
二、修正Action定义
首先检查你的trips.actions.ts文件,确保LoadTripsSuccess正确实现Action接口:
import { Action } from '@ngrx/store'; // 导入你的User类型,比如来自Firebase import { User } from 'firebase/auth'; // 先确认枚举里有LOAD_TRIPS_SUCCESS的定义 export enum TripsActionsTypes { LOAD_TRIPS = '[Trips] Load Trips', LOAD_TRIPS_SUCCESS = '[Trips] Load Trips Success' // 新增这个常量 } // LoadTrips action定义(如果还没写的话) export class LoadTrips implements Action { readonly type = TripsActionsTypes.LOAD_TRIPS; } // 重点修正LoadTripsSuccess export class LoadTripsSuccess implements Action { readonly type = TripsActionsTypes.LOAD_TRIPS_SUCCESS; // 必须有这个只读type属性 constructor(public payload: User) {} // 将user作为payload传递,方便后续reducer获取 } // 导出所有action类型,方便在Effects和Reducer中使用 export type TripsActions = LoadTrips | LoadTripsSuccess;
三、优化Effects代码
另外,你的Effects代码还有两个小细节可以优化:
- NgRx现在推荐使用管道式的
ofType操作符,而不是旧的actions$.ofType()写法 afAuth.authState会在用户登录/登出时触发,最好过滤掉用户未登录(null)的情况,避免派发无效action
修正后的TripsEffects:
import { Injectable } from '@angular/core'; import { Actions, Effect } from '@ngrx/effects'; import { switchMap, map, filter } from 'rxjs/operators'; import { AngularFireAuth } from '@angular/fire/auth'; import { TripsActionsTypes, LoadTripsSuccess } from './trips.actions'; @Injectable() export class TripsEffects { constructor( private actions$: Actions, private afAuth: AngularFireAuth ) {} @Effect() loadTrips$ = this.actions$.pipe( ofType(TripsActionsTypes.LOAD_TRIPS), switchMap(() => this.afAuth.authState.pipe( filter(user => !!user), // 只在用户登录后派发action map(user => new LoadTripsSuccess(user)) ) ) ); }
四、确认Effects模块注册
最后别忘了在你的根模块(比如AppModule)里注册Effects模块,否则你的TripsEffects不会生效:
import { NgModule } from '@angular/core'; import { EffectsModule } from '@ngrx/effects'; import { TripsEffects } from './trips.effects'; @NgModule({ imports: [ // ...其他导入的模块 EffectsModule.forRoot([TripsEffects]) // 注册你的Effects类 ] }) export class AppModule {}
按照上面的步骤修改后,应该就能解决这个错误了。
内容的提问来源于stack exchange,提问作者jack_snipe
相关产品推荐
相关产品推荐

