Can't get initial state, error: Type '{ workouts: Workout[]; } | null' is not assignable to type 'NgIterable<any> | null | undefined'

Can't get initial state, error: Type '{ workouts: Workout[]; } | null' is not assignable to type 'NgIterable<any> | null | undefined'

我试图在页面上显示我的应用程序的初始状态。 但是当我对状态数据进行 for 循环时,出现错误 Object is possibly 'null'.

向前迈出几步:*ngFor 现在看起来像这样 *ngFor="let workout of (workouts | async).workouts"。 当我删除 .workouts 时,错误变为 Type '{ workouts: Workout[]; } | null' is not assignable to type 'NgIterable<any> | null | undefined'

所以我假设我的应用程序由于某种原因无法获取初始状态。我检查了模型,所有类型的数据都是正确的。 我还用谷歌搜索了这个: 但似乎我做的一切都是对的。

现在代码:

workout.model.ts

import { Exercise } from "./exercise.model"

export interface Workout {
  name: string,
  exercises: Exercise[]
}

exercise.model.ts

export interface Exercise {
  name: string,
  completed: boolean
}

actions.ts

import { Action } from "@ngrx/store"
import { Workout } from "../models/workout.model"

export const ADD_WORKOUT       = 'ADD_WORKOUT'
export const REMOVE_WORKOUT    = 'REMOVE_WORKOUT'
export const UPDATE_WORKOUT    = 'UPDATE_WORKOUT'

export class AddWorkout implements Action {
  readonly type = ADD_WORKOUT

  constructor(public payload: Workout) {}
}

export type Actions = AddWorkout

reducer.ts

import * as WorkoutActions from "../actions/tasks.actions"

const initialState = {
  workouts: [{
    name: "Day 1",
    exercises: [{
      name: "push-up",
      completed: false
    }]
  }]
}

export function workoutsReducer(state = initialState, action: WorkoutActions.Actions) {
  switch(action.type) {
    case WorkoutActions.ADD_WORKOUT:
      return {
        ...state,
        workouts: [...state.workouts, action.payload]
       };
    default:
      return state;
  }
}

app.module.ts

  imports: [
    BrowserModule,
    StoreModule.forRoot({
      workoutsList: workoutsReducer
    } as ActionReducerMap<any,any>)
  ],

锻炼-list.component.ts

import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { Workout } from '../models/workout.model';

@Component({
  selector: 'app-workouts-list',
  templateUrl: './workouts-list.component.html',
  styleUrls: ['./workouts-list.component.scss']
})
export class WorkoutsListComponent implements OnInit {

  workouts!: Observable<{workouts: Workout[]}>;

  constructor(
    private store: Store<{workoutsList: {workouts: Workout[]}}>
  ) { }

  ngOnInit(): void {
    this.workouts = this.store.select('workoutsList')
  }

}

锻炼-list.component.html

<div *ngFor="let workout of (workouts | async).workouts">
  <div>{{workout.name}}</div>
</div>

我通过使用 optional chaining operator.

避免了 Object is possibly 'null'. 错误

在 for 循环中锻炼后尝试使用它。