如何在 Angular 中对商店实施错误处理

how to implement error handling on store in Angular

我正在处理现有的代码库,我的任务是在我的更新图表中实施错误处理,但不确定如何正确实施,因为我正在使用商店管理,所以如果我能得到任何,我将不胜感激关于我应该如何在商店中实施错误处理的建议或帮助。

我做了类似的事情,并通过在我的 ChartService.ts 文件中提供错误的 api 路由来测试它,但我没有收到错误消息,它总是说它“已保存" 无论我给出正确的 api 路线还是错误的 api 路线来更新图表。

我现在遇到的问题是,即使 api 或网络出现错误,它也没有给我错误消息。

import {Store} from '@ngrx/store';

  saveClick(){
    try
    {
      this.store.dispatch(updateChart({chart: this.chart}));
      this.snackbar.open("Changes to \"" + this.chart.name + "\" has been saved", "", { duration: 2500 });
    }
    catch(error)
    {
      this.snackbar.open("Error has occurred. Could not update Chart", "", { duration: 2500 });
    }
  }

Chart.effets.ts

    updateChart$ = createEffect(() => this.actions$.pipe(
        ofType(ChartActionTypes.UpdateChart),
        exhaustMap((props: { chart: Chart }) => this.chartService.updateChart(props.chart)//this.getChart(props)
            .pipe(
                // tap(c => console.log('TAPPY TAP', c)),
                map(chart => {
                    return chartLoaded({ chart: chart })
                }),
                catchError(() => EMPTY)
            ),
        )
    )
    )

HTML

    <button color="primary" mat-flat-button (click)="saveClick()" [disabled]="this.chart.isPublished">Save</button>

它不会 运行,但我在 stackblitz 中上传了该组件的所有代码,希望有人可以通过查看代码来帮助我。谢谢https://stackblitz.com/edit/angular-ivy-ncbmb4

你很接近:

  • 您的更新发送没问题
  • 您的图表加载正常
  • 你的 catchError 是错误的

请注意您发送操作以使用新数据更新您的商店的方式,当您遇到错误时,您需要执行相同的操作。

catchError((error: any, effect: Observable<Action>) => effect.pipe(startWith(chartUpdateError({ error }))))

所以这个新动作将使用减速器设置存储中的错误。现在要知道是否发生错误,您需要一个选择器来检查您刚刚在商店中更新的内容,这意味着您的 saveClick() 不处理任何这些。您可以在 ts 文件或 html 中订阅选择器,具体取决于您要做什么。我真的无法在语法方面帮助您,因为我不知道您的 reducer/action/selector 是什么样子。