Wil*_*ins 2 ngrx ngrx-effects angular ngrx-store
我试图从 api 获取错误消息并显示在我的表单输入中,以便用户可以看到正在提交的数据有什么问题。
来自 API 的响应:
{
"message": "The given data was invalid.",
"errors": {
"name": [
"This name is already in use."
]
}
}
Run Code Online (Sandbox Code Playgroud)
用户form.component.ts
this.store.dispatch(new actions.CreateUser(user));
Run Code Online (Sandbox Code Playgroud)
用户效果.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());
})
);
})
);
Run Code Online (Sandbox Code Playgroud)
如何获取该错误并将其传递回我的组件?
我应该在效果内部做喜欢并将其订阅到等待 CreateUserFail 错误的操作吗?我不确定这是否是一个好习惯,因为它会听取所有类型的操作。
我们构建了一个选择器并订阅了该选择器。
影响
@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)))
)
)
);
Run Code Online (Sandbox Code Playgroud)
减速器
case ProductActionTypes.CreateProductFail:
return {
...state,
error: action.payload
};
Run Code Online (Sandbox Code Playgroud)
选择器
export const getError = createSelector(
getProductFeatureState,
state => state.error
);
Run Code Online (Sandbox Code Playgroud)
成分
// Watch for changes to the error message
this.errorMessage$ = this.store.pipe(select(fromProduct.getError));
Run Code Online (Sandbox Code Playgroud)
模板
<div *ngIf="errorMessage$ | async as errorMessage" class="alert alert-danger">
Error: {{ errorMessage }}
</div>
Run Code Online (Sandbox Code Playgroud)
你可以在这里找到完整的例子:https : //github.com/DeborahK/Angular-NgRx-GettingStarted/tree/master/APM-Demo4
| 归档时间: |
|
| 查看次数: |
780 次 |
| 最近记录: |