我有以下代码
selectProduct(id){
const sub = this.store$.select(ProductStoreSelector.selectProductByID(id)).subscribe((product) => {
this.store$.dispatch(new ProductStoreAction.SetSelectedProduct({productID: product.id}));
sub.unsubscribe();
});
}
基本上,我想获取我的产品列表,并按ID获取一个,然后更改我的商店状态,以便selectedProduct成为我刚刚选择的产品
export const featureAdapter: EntityAdapter<IProduct> = createEntityAdapter<IProduct>({
selectId: model => model.id,
});
export const selectAllProducts: (state: object) => Array<IProduct> = featureAdapter.getSelectors(selectProductsState).selectAll;
export const selectProductByID = (id: string) => createSelector(
selectAllProducts,
(products) => products.find((product) => product.id === id)
);
并且我的商店是选择了一个商品的EntityState
export interface State extends EntityState<IProduct> {
selectedProduct: IProduct;
}
但是问题是,
althougt我确实得到了我的productId,我无法取消订阅sub.unsubscribe()
,因为它是未定义的。
答案 0 :(得分:0)
您可以使用任一take(1)仅监听一次值。否则,请尝试退订,如下所示:
selectProduct(id){
this.store$.select(ProductStoreSelector.selectProductByID(id)).subscribe((product) => {
this.store$.dispatch(new ProductStoreAction.SetSelectedProduct({productID: product.id}));
}).unsubscribe();
}
使用take(1):
selectProduct(id){
this.store$.select(ProductStoreSelector.selectProductByID(id))
.take(1)
.subscribe((product) => {
this.store$.dispatch(new ProductStoreAction.SetSelectedProduct({productID: product.id}));
});
}