如何处理来自 ngrx effect 的 catch 块的错误并将其发送到组件中?
Posted
技术标签:
【中文标题】如何处理来自 ngrx effect 的 catch 块的错误并将其发送到组件中?【英文标题】:How to handle errors from ngrx effect 's catch block and send it to store in component? 【发布时间】:2022-01-14 01:49:57 【问题描述】:我想处理来自我的组件的加载失败场景,以便我可以处理视图 html 中的无数据。我应该为错误场景添加选择器还是在效果中处理它。我对基于操作获取数据的 ngrx 风格非常陌生
相关文件
查看所有组件.ts
export class ViewAllOperatorsComponent implements OnInit, OnDestroy
readonly componentDestroyed: Subject<void> = new Subject();
data: OperatorRow[] = [];
columns: Column[];
tableOptions: TableOptions;
constructor(private store: Store<OperatorsState>, private helpContextService: HelpContextService)
this.columns = [
//body of columns
];
this.tableOptions =
rowActions: [
action: () => null,
actionRendererComponent: () => OperatorRowActionComponent
]
;
this.store
.select(OperatorSelectors.selectOperatorRows)
.pipe(takeUntil(this.componentDestroyed))
.subscribe((rows) => (this.data = rows));
ngOnInit(): void
this.store.dispatch(OperatorActions.loadOperators());
ngOnDestroy(): void
this.componentDestroyed.next();
this.componentDestroyed.complete();
Operator-action.ts
export const loadOperators = createAction("[Operator] Load Operators");
export const loadOperatorsSuccess = createAction("[Operator] Load Operators Success", props< data: OperatorRow[] >());
export const loadOperatorsFailure = createAction("[Operator] Load Operators Failure", props< error: any >());
算子效果.ts
@Injectable()
export class OperatorEffects
loadOperators$ = createEffect(() =>
return this.actions$.pipe(
ofType(OperatorActions.loadOperators),
concatMap(() =>
this.operatorManagementService.findOperators().pipe(
map((items) => items.map((item) => new OperatorRow(item))),
map((data) => OperatorActions.loadOperatorsSuccess( data )),
catchError((error: unknown) => of(OperatorActions.loadOperatorsFailure( error )))
)
)
);
);
【问题讨论】:
【参考方案1】:向 NgRx 存储添加错误状态是最直接的方法。使用选择器,您可以读取错误状态并重新渲染组件。
Brandon Roberts 写了一篇详细的文章并提供了一些替代方案,有关更多信息,请参阅 https://brandonroberts.dev/blog/posts/2019-03-04-handling-error-states-with-ngrx/
【讨论】:
我在reducer中添加了错误选择器并添加了错误条件,并使用组件中的错误选择器订阅了商店以上是关于如何处理来自 ngrx effect 的 catch 块的错误并将其发送到组件中?的主要内容,如果未能解决你的问题,请参考以下文章
如何处理来自 Presenter 的 Datagrid 列的事件?
Android/Parse-如何处理来自 ParseQuery 的多个回调