我正在 Angular 12 和最新的 NgRx 库中创建一个应用程序,用于教程目的。我有以下模型、动作、reducer 和应用程序状态类。
模型
export interface Tutorial {
name: string;
url: string;
}
行动
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
减速器
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;
}
}
应用状态
import { Tutorial } from "./_models/tutorial.model";
export interface AppState {
readonly tutorial: Tutorial[];
}
现在我想在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 { }
但是在app.module.ts文件中,导入 reducer 会导致错误。错误如下所示:
错误:src/app/app.module.ts:19:29 - 错误 TS2322:类型 '(state: Tutorial[] | undefined, action: Actions) => Tutorial[]' 不可分配给类型 'ActionReducer<Tutorial[ ],动作>'。参数“action”和“action”的类型不兼容。类型“动作”不可分配给类型“动作”。“Action”类型中缺少属性“payload”,但在“RemoveTutorial”类型中是必需的。
19 StoreModule.forRoot({教程:reducer}),~~~~~~~~
src/app/_actions/tutorial.actions.ts:20:17 20 构造函数(公共负载:数字){} ~~~~~~~~~~~~~~~~~~~~~~ 'payload'在这里声明。
由于我是 NgRx 的新手,我不明白为什么会出现问题。请帮我解决问题。