我试图从api中获取错误消息并在我的表单输入中显示,以便用户可以看到正在提交的数据有什么问题。
来自API的回复:
{
"message": "The given data was invalid.",
"errors": {
"name": [
"This name is already in use."
]
}
}
用户form.component.ts
this.store.dispatch(new actions.CreateUser(user));
user.effect.ts
@Effect()
CreateUser$: Observable<Action> = this.actions$.pipe(
ofType(UserActions.CREATE_USER),
map((action: UserActions.CreateUser) => action.payload),
switchMap(payload => {
return this.userService.save(payload).pipe(
map((user: User) => {
return new UserActions.CreateUserSuccess(user);
}),
catchError(err => {
return of(new UserActions.CreateUserFail());
})
);
})
);
如何获取该错误并将其传递回我的组件?
我应该在效果中做什么并将其订阅到等待CreateUserFail错误的Actions?我不确定它是否是一个好的做法,因为它会听取各种行为。
我们构建了一个选择器并订阅了该选择器。
影响
@Effect()
createProduct$: Observable<Action> = this.actions$.pipe(
ofType(productActions.ProductActionTypes.CreateProduct),
map((action: productActions.CreateProduct) => action.payload),
mergeMap((product: Product) =>
this.productService.createProduct(product).pipe(
map(newProduct => (new productActions.CreateProductSuccess(newProduct))),
catchError(err => of(new productActions.CreateProductFail(err)))
)
)
);
减速器
case ProductActionTypes.CreateProductFail:
return {
...state,
error: action.payload
};
选择
export const getError = createSelector(
getProductFeatureState,
state => state.error
);
零件
// Watch for changes to the error message
this.errorMessage$ = this.store.pipe(select(fromProduct.getError));
模板
<div *ngIf="errorMessage$ | async as errorMessage" class="alert alert-danger">
Error: {{ errorMessage }}
</div>
你可以在这里找到完整的例子:https://github.com/DeborahK/Angular-NgRx-GettingStarted/tree/master/APM-Demo4
应该足以改变catchError,如下所示:
catchError(err => {
return new UserActions.CreateUserFail(err);
})
还考虑使用隐式返回:
map( (user: User) => new UserActions.CreateUserSuccess(user) ),
catchError( err => new UserActions.CreateUserFail(err) )