[英]Select and update the additional property of NgRx entity using component store
[英]Store value update change not detected on subscribe using NgRx component store in angular
我在 angular 应用程序中使用 NgRx 组件存储,如下所示
export interface ProductCategoryState {
categories: CategoryModel[];
category: CategoryModel;
}
@Injectable()
export class ProductCategoryStore extends ComponentStore<ProductCategoryState> {
constructor(private iGenericHttpClient: IGenericHttpClient<any>, private globalFacade: GlobalFacade) {
super(initialState);
}
readonly getCategories$: Observable<CategoryModel[]> = this.select((state) => state.categories);
private readonly setCategories = this.updater((state, categories: CategoryModel[]) => ({
...state,
categories: categories
}));
readonly delete = this.effect((id$: Observable<string>) => {
return id$.pipe(
withLatestFrom(this.getCategories$),
switchMap(([id, categories]) => {
return this.iGenericHttpClient.delete(`/category/${id}`).pipe(
tapResponse(
() => {
const index = categories.findIndex((x) => x.id == id);
categories.splice(index, 1);
this.setCategories(categories);
}
)
);
})
);
});
}
在删除操作中,找到索引并删除记录,并更新 state,但是,在如下所示的组件之一中的订阅上未检测到更新。
@Component({
.......,
providers: [ProductCategoryStore]
})
export class ProductCategoryComponent implements OnInit {
constructor(private productCategoryStore: ProductCategoryStore) {}
ngOnInit(): void {
this.productCategoryStore.getCategories$.subscribe((dataSource) => {
console.log(dataSource);
});
}
}
我认为您需要将一个新数组传递给您的更新 function。 您当前正在更新现有数组并传递现有引用。
尝试这个:
const updatedCategories = categories.filter(x => x.id !== id);
this.setCategories(updatedCategories);
我通过这样做实现了上述目标
private readonly deleteCategory = this.updater((state, id: string) => ({
...state,
categories: state.categories.filter((category) => {
if (category.id === id) return false;
return true;
})
}));
并调用如下
readonly delete = this.effect((id$: Observable<string>) => {
return id$.pipe(
switchMap((id) => {
return this.iGenericHttpClient.delete(`/category/${id}`).pipe(
tapResponse(
() => {
this.deleteCategory(id);
},
)
);
})
);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.