求助:将旧版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
相关产品推荐
相关产品推荐

