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

求助:将旧版NgRx Effect代码升级适配NgRx Effects v15

NgRx Effects v15 适配方案

以下是适配后的代码,关键变化点会在代码后说明:

import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { MatSnackBar } from '@angular/material/snack-bar';
import { tap, map, delay } from 'rxjs/operators';
import { SNACKBAR_CLOSE, SNACKBAR_OPEN, SnackbarOpen, SnackbarClose } from './your-action-file-path'; // 替换为实际的action文件路径

@Injectable()
export class SnackbarEffects {

  closeSnackbar$ = createEffect(() => 
    this.actions$.pipe(
      ofType(SNACKBAR_CLOSE),
      tap(() => this.matSnackBar.dismiss())
    ),
    { dispatch: false }
  );

  showSnackbar$ = createEffect(() => 
    this.actions$.pipe(
      ofType<SnackbarOpen>(SNACKBAR_OPEN),
      map(action => action.payload),
      tap(payload => this.matSnackBar.open(payload.message, payload.action, payload.config)),
      delay(2000),
      map(() => new SnackbarClose())
    )
  );

  constructor(
    private actions$: Actions,
    private matSnackBar: MatSnackBar
  ) {}
}

关键适配点

  • 弃用@Effect装饰器,改用createEffect函数创建effect
  • actions.ofType()替换为ofType()操作符,需从@ngrx/effects导入
  • 无需显式声明Observable类型,TypeScript会自动推断
  • 无action派发的effect(原dispatch: false),需在createEffect的第二个参数中指定{ dispatch: false }
  • 变量名建议以$结尾,这是RxJS Observable变量的约定俗成命名方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:47:06