从商店中移除项目在 NgRx 中不起作用

Removing item from store is not working in NgRx

我正在学习 NgRx。所以我创建了一个小应用程序。有两个文本字段用于添加项目和将项目显示为列表。我可以将项目添加到列表中。但我无法从列表中删除该项目。这是代码:

操作:

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 TutorialActions = AddTutorial | RemoveTutorial

减速器:

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 tutorialReducer(state: Tutorial[] = [initialState], action: TutorialActions.TutorialActions) {
    switch(action.type) {
        case TutorialActions.ADD_TUTORIAL:
            return [...state, action.payload];
        
        case TutorialActions.REMOVE_TUTORIAL:
            state.splice(action.payload, 1)
            return state;
            
        default:
            return state;
    }
}

列表组件:

<div class="right" *ngIf="tutorials">

  <h3>Tutorials</h3>
  <ul>
    <li (click)="delTutorial(i)" *ngFor="let tutorial of tutorials | async; let i = index">
      <!-- <a [href]="tutorial.url" target="_blank">{{ tutorial.name }}</a> -->
      {{ tutorial.name }}
    </li>
  </ul>
</div>

TS 文件:

import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { AppState } from '../app.state';
import { Tutorial } from '../_models/tutorial.model';
import * as TutorialActions from './../_actions/tutorial.actions';

@Component({
  selector: 'app-read',
  templateUrl: './read.component.html',
  styleUrls: ['./read.component.css']
})
export class ReadComponent implements OnInit {

  tutorials!: Observable<Tutorial[]>;

  constructor(private store: Store<AppState>) {
    this.tutorials = store.select('tutorial');
  }

  delTutorial(index: number) {
    this.store.dispatch(new TutorialActions.RemoveTutorial(index) )
  }

  ngOnInit(): void {
  }

}

每当我点击列表删除项目时,我都会收到以下错误:

最后,我找到了解决办法。下面是 reducer 函数的代码:

export function tutorialReducer(state: Tutorial[] = [initialState], action: TutorialActions.TutorialActions) {
    switch(action.type) {
        case TutorialActions.ADD_TUTORIAL:
            return [...state, action.payload];
        
        case TutorialActions.REMOVE_TUTORIAL:
            const index = action.payload;
            return [...state.slice(0, index), ...state.slice(index + 1)];    
                                    
        default:
            return state;
    }
}