mnu*_*sir 1 ngrx angular ngrx-reducers
我正在 Angular 12 和最新的 NgRx 库中创建一个应用程序以供参考。我有以下模型、操作、减速器和应用程序状态类。
模型
export interface Tutorial {
name: string;
url: string;
}
Run Code Online (Sandbox Code Playgroud)
行动
import { Injectable } from '@angular/core'
import { Action } from '@ngrx/store'
import { Tutorial } from '../_models/tutorial.model'
export const ADD_TUTORIAL = '[TUTORIAL] Add'
export const REMOVE_TUTORIAL = '[TUTORIAL] Remove'
export class AddTutorial implements Action {
readonly type = ADD_TUTORIAL
constructor(public payload: Tutorial) {}
}
export class RemoveTutorial implements Action {
readonly type = REMOVE_TUTORIAL
constructor(public payload: number) {}
}
export type Actions = AddTutorial | RemoveTutorial
Run Code Online (Sandbox Code Playgroud)
减速器
import { Action } from '@ngrx/store'
import { Tutorial } from '../_models/tutorial.model';
import * as TutorialActions from './../_actions/tutorial.actions'
const initialState: Tutorial = {
name: 'Initial Tutorial',
url: 'http://google.com'
}
export function reducer(state: Tutorial[] = [initialState], action: TutorialActions.Actions) {
switch(action.type) {
case TutorialActions.ADD_TUTORIAL:
return [...state, action.payload];
default:
return state;
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序状态
import { Tutorial } from "./_models/tutorial.model";
export interface AppState {
readonly tutorial: Tutorial[];
}
Run Code Online (Sandbox Code Playgroud)
现在我想在app.module.ts文件中导入减速器。这是代码:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { StoreModule } from '@ngrx/store';
import { reducer } from './_reducers/tutorial.reducer';
import { ReadComponent } from './read/read.component';
import { CreateComponent } from './create/create.component';
@NgModule({
declarations: [
AppComponent,
ReadComponent,
CreateComponent
],
imports: [
BrowserModule,
StoreModule.forRoot({ tutorial: reducer }),
AppRoutingModule,
],
providers: [],
bootstrap: [
AppComponent
]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
但是在app.module.ts文件中,导入reducer会导致错误。错误如下图所示:
错误:src/app/app.module.ts:19:29 - 错误 TS2322:类型 '(state: Tutorial[] | undefined, action: Actions) => Tutorial[]' 不可分配给类型 'ActionReducer<Tutorial[ ],动作>'。参数“action”和“action”的类型不兼容。类型“Action”不可分配给类型“Actions”。“Action”类型中缺少属性“payload”,但“RemoveTutorial”类型中需要属性“payload”。
19 StoreModule.forRoot({教程:reducer}),~~~~~~~~~
src/app/_actions/tutorial.actions.ts:20:17 20 构造函数(公共有效负载:数字){} ~~~~~~~~~~~~~~~~~~~~~~ '有效负载'在这里声明。
由于我是 NgRx 的新手,我不明白为什么会出现这个问题。请帮我解决这个问题。
自从我使用该语法以来已经有一段时间了,它可能是一个回归错误。您可以将其断言为ActionReducerMap
StoreModule.forRoot({ tutorial: reducer } as ActionReducerMap<any,any>)
Run Code Online (Sandbox Code Playgroud)
另外,我建议看一下 createAction 和 createReducer 语法 - 它使事情变得更简单。
| 归档时间: |
|
| 查看次数: |
1103 次 |
| 最近记录: |