加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 当状态发生变化时未调用ngrx存储订阅

发布时间:2020-12-17 06:49:35 所属栏目:安全 来源:网络整理
导读:我正在使用我的服务中定义的虚拟数据创建一个应用程序. 在一个组件中,我有以下删除产品的功能: removeItem(productId: string) { this.cartService.removeItem(productId); } 和服务如下: removeItem(productId: string) { const itemIndex = this.cart.pr
我正在使用我的服务中定义的虚拟数据创建一个应用程序.

在一个组件中,我有以下删除产品的功能:

removeItem(productId: string) {
      this.cartService.removeItem(productId);
  }

和服务如下:

removeItem(productId: string) {
    const itemIndex = this.cart.products.findIndex(el => el.id === productId);
    if (itemIndex > -1) {
      this.cart.products.splice(itemIndex,1);
      return Observable.of(this.cart)
        .subscribe((cartResponse: Cart) => {
          this.store.dispatch({ type: CART_UPDATE,payload: cartResponse });
        });
    }
  }

(this.cart是我在服务中硬编码的数据).

我的减速机看起来像:

export const cartReducer = (state: Cart = {} as Cart,{type,payload}) => {
  switch (type) {

    case CART_UPDATE:
      // update categories state
      return payload;
    default:
      return state;
  }
};

然后我订购了一个组件中的购物车,如:

ngOnInit() {
    this.store.select('cart').subscribe((cart: Cart) => {
      console.log('here');
      this.numberOfItems = cart.products.length;
    });
  }

我也有app.module

StoreModule.provideStore({
  cart: cartReducer
}),

remove函数工作正常,代码使用正确的有效负载到达reducer函数.

问题是组件中的订阅回调仅在第一次加载组件时调用.

当我调用remove函数时,确实删除了产品并调用了reducer函数并返回了正确的数据,但是没有调用回调函数.

我错过了什么吗?

解决方法

我认为问题是你在reducer中返回的有效负载与现有状态具有相同的对象引用.尝试返回一个新对象,看看是否会导致您的订阅被调用.像这样:

export const cartReducer = (state: Cart = {} as Cart,payload}) => {
  switch (type) {    
    case CART_UPDATE:
      // update categories state
      return { ...payload }; // equivalent to Object.assign({},payload);
    default:
      return state;
  }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读