如何在 behaviorsubject 中保存初始数据的状态?

How to save state of initial data in behaviorsubject?

我在 private roles$ = new BehaviorSubject<Role[]>([]); 从服务器加载了初始角色数组。

我读 roles$ 并映射到组件内部的局部变量:

public localRoles: Observable<Role[]>;
this.localRoles = this.service.roles$;

还有方法checkAll()改变roles$。如何在任何更改后保存 roles$ 的初始状态?

checkAll() {
  this.localRoles.pipe(map((l) => { l.checked = true; return l;});
}

所以,当更改 this.localRoles 我想将它与 roles$ 合并以获得最后的更改。

但在某些地方我仍然需要获得 roles$ 的初始状态(没有更改)。

我找到了一个解决方案,你觉得怎么样?:

this.localRoles = this.service.roles$.pipe(
            map((roles: Role[])=> {
                  if(CHANGES$.getValue()) return CHANGES$.getValue();
                  return roles;
            }),
        );

将更改存储在另一个流中CHANGES$ 然后当读取状态存在时 return 初始状态。

如果我理解问题,你可以这样做。它使用扫描运算符来维护购物车项目列表。

(此应用程序是一个购物车,可以添加、更新或删除购物车中的商品。)

  // Add item action (Actions: Add, update, delete)
  private itemSubject = new Subject<Action<CartItem>>();
  itemAction$ = this.itemSubject.asObservable();

  cartItems$ = this.itemAction$
    .pipe(
      scan((items, itemAction) => this.modifyCart(items, itemAction), [] as CartItem[])
    );

以下是根据用户操作发出操作的例程:

  // Add the vehicle to the cart as an Action<CartItem>
  addToCart(vehicle: Vehicle): void {
    this.itemSubject.next({
      item: { vehicle, quantity: 1 },
      action: 'add'
    });
  }

  // Remove the item from the cart
  removeFromCart(cartItem: CartItem): void {
    this.itemSubject.next({
      item: { vehicle: cartItem.vehicle, quantity: 0 },
      action: 'delete'
    });
  }

  updateInCart(cartItem: CartItem, quantity: number) {
    this.itemSubject.next({
      item: { vehicle: cartItem.vehicle, quantity },
      action: 'update'
    });
  }

这里是对发出的购物车项目数组执行适当操作的方法:

  // Return the updated array of cart items
  private modifyCart(items: CartItem[], operation: Action<CartItem>): CartItem[] {
    if (operation.action === 'add') {
      return [...items, operation.item];
    } else if (operation.action === 'update') {
      return items.map(item => item.vehicle.name === operation.item.vehicle.name ? operation.item : item)
    } else if (operation.action === 'delete') {
      return items.filter(item => item.vehicle.name !== operation.item.vehicle.name);
    }
    return [...items];
  }

基本上,每次用户选择将商品添加到购物车时,都会创建一个包含新商品的新数组并发出新数组。

当用户选择更新时,项目位于数组中并被更新的项目替换。

当用户选择删除时,数组被过滤以包括所有被删除的项目。

注意:我使用的终点没有 ID,因此使用车辆名称作为键(这通常不是一个好主意)。

这与您的目标接近吗?