Angular 15 Ngrx 存储/效果

问题描述 投票:0回答:1

我尝试了一段时间,尝试了很多不同的事情,但我就是找不到解决方案,为什么会这样

  constructor(protected subjectService: SubjectsService,
              protected userService: UsersService,
              protected languageService: LanguageService,
              protected translate: TranslateService,
              protected gradeService: GradeService,
              private store: Store<{ subjectGrades: SubjectGrade[], subject: Subject[] }>) {

    if (this.userService.getLoggedInUser().admin) {
      this.displayedColumns = ['subject', 'avgGrade', 'actions'];
    }
    this.subjects$ = this.store.select('subject');
    this.subjectGrades$ = this.store.select('subjectGrades');
    this.updateSubjectsAndAVGGrades();
  }


  updateSubjectsAndAVGGrades(): void {
    this.subjects$
      .pipe(
        takeUntil(this.subscriptions),
        switchMap((subjects: Subject[]) => {
          this.subjects = subjects;
          console.log('subjects', subjects);
          return this.subjectGrades$.pipe(
            takeUntil(this.subscriptions),
            map((grades: SubjectGrade[]) => {
              return subjects.map(subject => {
                const subjectGrades = grades.filter(grade => grade.subject.id === subject.id);
                return this.gradeService.calculateAvgGrades(subjectGrades);
              });
            })
          );
        })
      )
      .subscribe((avgGrades: Grade[]) => {
        this.avgGrades = avgGrades;
      });
  }

不知何故存在未定义成绩或科目的情况。

我刚刚在我的Reducer、Action、Effect 中调试了几个小时,所有数据都完美传递。我在 AppComponent 中加载两个初始状态,初始状态基于从后端获取的 http。

angular ngrx-store ngrx-effects
1个回答
0
投票

发现问题是因为当我在reducer中定义状态时,有时会发生这样的情况,因为它是异步的,所以传输的数据是未定义的,所以数组最终是未定义的。为了解决这个问题,我添加了一个检查,检查其未定义状态是否变成空数组。

on(loadSubjectGradesSuccess, (state, {subjectGrades}) => { if (subjectGrades === undefined) return state; return subjectGrades; }),

© www.soinside.com 2019 - 2024. All rights reserved.