ngrx心得体会总结
一个典型的场景:添加店铺商品,其中店铺有多个,每个店铺有不同的商品分类,商品分类可以多级!
@Injectable()
export class AppEffects {
// 添加店铺商品
@Effect()
StartAddShopGoods$ = this.ofType(ActionTypes.StartAddShopGoods).pipe(
takeUntil(this.ofType(ActionTypes.Error).pipe(
tap(res => console.log('发生了点错误'))
)),
switchMap(res => {
// 加载店铺
this.store.dispatch(new SearchShop());
this.router.navigate(['/select-shop'], { replaceUrl: false, skipLocationChange: true });
// 添加选择店铺
return this.ofType(ActionTypes.SelectShop).pipe(
switchMap(res => {
// 加载店铺商品分类
this.store.dispatch(new SearchShopGoodsCategory());
this.router.navigate(['/select-shop-goods-category'], { replaceUrl: false, skipLocationChange: true });
// 选择店铺商品分类
return this.ofType(ActionTypes.SelectShopGoodsCateogry).pipe(
tap(res => {
// 商品信息
this.router.navigate(['/shop-goods-edit'], { replaceUrl: false, skipLocationChange: true });
}),
switchMap(res => {
// 点击提交按钮
return this.ofType(ActionTypes.AddShopGoods).pipe(
switchMap(res => this.util.wpost('iwe7ShopGoods', 'Upsert', {}).pipe(
map(res => {
// 添加成功
this.router.navigate(['/user-center'], { replaceUrl: false, skipLocationChange: true });
return new AddSuccessShopGoods();
})
))
);
})
);
})
);
})
);
// 公共加载
@Effect()
SearchShop$ = this.ofType(ActionTypes.SearchShop).pipe(
switchMap(res => {
return this.util.wpost('iwe7Shop', 'Loads', {}).pipe(
pluck('data'),
pluck('list')
);
}),
map(res => {
return new SearchSuccessShop(res);
})
);
@Effect()
SearchShopGoodsCategory$ = this.ofType(ActionTypes.SearchShopGoodsCategory).pipe(
switchMap(res => {
return this.util.wpost('iwe7ShopGoodsCategory', 'Loads', {}).pipe(
pluck('data'),
pluck('list')
);
}),
map(res => {
return new SearchSuccessShopGoodsCategory(res);
})
);
constructor(
private actions$: Actions,
private store: Store<any>,
private util: Iwe7Util2Service,
private router: Router
) { }
ofType<T extends Action>(name: string): Actions<T> {
return this.actions$.ofType<T>(name);
}
}
复制代码
总结: actions 定义操作 effects 串联actions,完成业务逻辑 reducers 操作Store model 定义结构