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

Angular 18中实现NgRx Effect时遇Cannot read properties of undefined(pipe)错误

解决NgRx Cannot read properties of undefined (reading 'pipe') 错误

核心问题分析

你的代码存在两个关键问题,直接导致了该错误:

  1. createEffect 的回调函数未返回 Observable 流
  2. 未确认 Actions 服务是否正确注入到 Effects 类中

具体修复步骤

1. 确保 Effects 类正确注入 Actions 服务

你的 Effects 类必须在构造函数中注入 NgRx 的 Actions 服务,否则 this.actions$ 会是 undefined:

import { Actions, createEffect, ofType } from '@ngrx/effects';
import { Injectable } from '@angular/core';
import { UserService } from './path-to-user-service';

@Injectable()
export class UserEffects {
  // 构造函数中注入 Actions 和 UserService
  constructor(
    private readonly actions$: Actions,
    private readonly userService: UserService
  ) {}

  // 下面是你的 register$ 效果
  register$ = createEffect(() => {
    // ... 修复后的代码
  });
}

2. 给 createEffect 回调添加 return 语句

当前代码中,回调函数没有返回 this.actions$.pipe(...) 生成的 Observable 流,导致 createEffect 无法获取有效数据流,引发错误:

register$ = createEffect(() => {
  // 必须返回这个 Observable 流
  return this.actions$.pipe(
    ofType(registerUser),
    mergeMap(action =>
      this.userService.userRegister(
        action.firstName,
        action.lastName,
        action.email,
        action.phone,
        action.password
      ).pipe(
        map(user => registerUserSuccess({ user: user }))
      )
    )
  );
});

注意:无需手动指定 :any 类型,TypeScript 可自动推断返回类型。

3. 额外检查:确认 UserService 注入正常

确保 UserService 已在 Angular 依赖注入系统中注册(比如添加 @Injectable({ providedIn: 'root' }) 装饰器),且已正确注入到 Effects 类的构造函数中,避免后续调用 userRegister 时出现新的 undefined 问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 06:42:33