You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NgRx Effect中注入的actions$出现undefined问题的求助

解决NgRx Effect中this.actions$为undefined的问题

我之前也碰到过一模一样的问题!折腾了大半天才找到根源,你的代码里有两个关键问题:

  • 类属性初始化时机不对
    你现在的createTodos$是类的直接属性,它会在constructor执行之前就完成初始化——这时候Angular还没把actions$注入到类里,所以this.actions$自然是undefined。
    正确的写法是给createEffect传一个箭头函数,让它在NgRx真正初始化Effect的时候才执行(这时候constructor已经跑完,依赖都注入好了):

    createTodos$ = createEffect(() => this.actions$.pipe(
      ofType(CREATE_TASK),
      map(() => {
        console.log('called');
        return { type: 'OTHER'};
      })
    ));
    
  • 注入类型错误
    你构造函数里注入的是Action类型,但NgRx的动作流应该注入Actions(注意是复数形式),这个类型来自@ngrx/effects包。类型写错的话,Angular的DI系统没法正确解析依赖,也会导致actions$为undefined。修正后的构造函数:

    constructor(private readonly actions$: Actions) { }
    

完整修正后的代码

import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { map } from 'rxjs/operators';
// 记得导入你的CREATE_TASK动作
import { CREATE_TASK } from './your-actions-file';

@Injectable()
export class AmazingEffects {
  createTodos$ = createEffect(() => this.actions$.pipe(
    ofType(CREATE_TASK),
    map(() => {
      console.log('called');
      return { type: 'OTHER'};
    })
  ));

  constructor(private readonly actions$: Actions) { }
}

这两个问题都解决后,你的Effect应该就能正常触发了,当时我也是卡了好久才意识到初始化时机的坑😂

内容的提问来源于stack exchange,提问作者Dreamweaver

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 08:37:35