Rx.js 无法获取过去的值

Rx.js can't get past values

我正在尝试获取发出的最后 3 个值,使用下面的代码我期望在填充 uiOrder 并调用 cancelOrderItem() 几次之后,我可以使用 getHistory() 访问订单的最后 3 个修订版,但实际上我得到了最后一个(当前)值 3 次,我尝试过 replaySubject(3) 得到相同的结果。 这是我的代码:

export class OrdersService {

  public readonly orders: Observable<Order[]>;
  public readonly uiOrder: Observable<Order>;

  private _orders: BehaviorSubject<Order[]>;
  private _uiOrder: BehaviorSubject<Order>;

  private dataStore: {
    uiOrder: Order,
    orders: Order[]
 };


  constructor() {

    this.dataStore = {
      uiOrder: null,
      orders: []
    };

    this._orders = <BehaviorSubject<Order[]>>new BehaviorSubject([]);
    this._uiOrder = <BehaviorSubject<Order>>new BehaviorSubject({});
    this.orders = this._orders.asObservable();
    this.uiOrder = this._uiOrder.asObservable();
  }

  getOrder(orderId: number | string) {
    for (let i = 0; i < this.dataStore.orders.length; i++) {
      if (this.dataStore.orders[i].id == orderId) {
        this.dataStore.orders[i].lastAccess = moment().format().slice(0, 19) + 'Z';
        this.dataStore.uiOrder = this.dataStore.orders[i];
        this.updateUiOrder();
      }
    }
  }


  cancelOrderItem(action) {
    this.dataStore.uiOrder.sections[action.sectionIndex].orderDetails.splice(action.orderDetailsIndex, 1);
    this.updateUiOrder()
  }

  getHistory() {
    this.uiOrder.take(3).subscribe((res) => {
      console.log('uiOrder', res);
    }).unsubscribe()
  }

  updateUiOrder() {
    console.log('updating ui order');
    this._uiOrder.next(this.dataStore.uiOrder);
  }

}

我做错了什么?

getHistory() {
this.uiOrder.takeLast(3).subscribe((res) => {
  console.log('uiOrder', res);
}).unsubscribe()  }

takeLast 运算符检索从源可观察对象发出的最后三个值。

你可能想多了。如果您需要随时可用的最新 3 个订单,为什么不将它们存储在每次 uiOrder 发出新订单时更新的数组中?

orderHistory:Order[] = [];

orders$ = this.uiOrder.subscribe(order =>
   let h = this.orderHistory;
   //add the order to history array:
   h = [...h, order];
   //splice the array to keep only the last 3 orders:
   if (h.length > 3) h.splice(0,h.length-3)
);

现在,如果您想知道最近的 3 个订单,只需查看 orderHistory。作为奖励,该查找是一个同步操作。

您正在寻找的运算符是 bufferCount(3,1),它创建了最后 3 个发出的值的滑动 window。缺点:它只会在累积 3 个值后才开始发射。如果你想获得第一个值,你可以这样做:

Rx.Observable.from([null,null])
  .concat(this.uiOrder)
  .bufferCount(3,1)
  .subscribe(uiOrderHistory => ... );

这样您的弹珠图将如下所示:

---Order1-----------------Order2--------------------Order3
bufferCount(3,1)
---[null,null,Order1]-----[null,Order1,Order2]------[Order1,Order2,Order3]