简体   繁体   English

使用 angular 中的 NgRx 组件存储进行订阅时未检测到存储值更新更改

[英]Store value update change not detected on subscribe using NgRx component store in angular

I am using NgRx component store in the angular application as below我在 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);
            }
          )
        );
      })
    );
  });
}

On the delete operation, find the index and deleted the record, and update the state, however, the update is not detected on Subscribe in one of the components as shown below.在删除操作中,找到索引并删除记录,并更新 state,但是,在如下所示的组件之一中的订阅上未检测到更新。

@Component({
  .......,
  providers: [ProductCategoryStore]
})
export class ProductCategoryComponent implements OnInit {
  constructor(private productCategoryStore: ProductCategoryStore) {}
  ngOnInit(): void {
    this.productCategoryStore.getCategories$.subscribe((dataSource) => {
      console.log(dataSource);
    });
  }
}

I think you need to pass a new array to your update function.我认为您需要将一个新数组传递给您的更新 function。 You are currently updating the existing array and passing the existing reference.您当前正在更新现有数组并传递现有引用。

Try this:尝试这个:

const updatedCategories = categories.filter(x => x.id !== id);
this.setCategories(updatedCategories);

I achieved the above by doing this我通过这样做实现了上述目标

  private readonly deleteCategory = this.updater((state, id: string) => ({
    ...state,
    categories: state.categories.filter((category) => {
      if (category.id === id) return false;
      return true;
    })
  }));

And call as below并调用如下

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM