Rx.js struggles to access historical values

Seeking assistance with retrieving the last 3 values emitted. Despite using the provided code to populate uiOrder and invoking cancelOrderItem() multiple times, I am unable to access the last 3 revisions of the order via getHistory(). Instead, I receive the current value three times consecutively. Even attempting replaySubject(3) yields the same outcome.


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);
    }

}

What could be causing this issue?

Answer №1

If you are searching for the specific operator, it is bufferCount(3,1). This operator creates a sliding window of the last 3 values emitted. The only downside is that it will start emitting only after accumulating 3 values. To include the first value as well, you can use the following approach:

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

This arrangement will result in a marble diagram like this:

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

Answer №2

Perhaps you are overanalyzing the situation. Instead of constantly searching for the latest 3 orders, consider storing them in an array that is updated every time a new order is emitted by uiOrder.

orderList: Order[] = [];

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

Now, whenever you need to access the most recent 3 orders, simply refer to the orderList. This approach also ensures synchronous operation.

Answer №3

fetchRecentData() {
this.latestData.takeLast(3).subscribe((data) => {
  console.log('Latest data', data);
}).unsubscribe()
}

takeLast  method fetches the most recent three data points from the latest dataset.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The module '@angular/core' could not be located in the '@angular/platform-browser' and '@angular/platform-browser-dynamic' directories

Attempting to incorporate Angular 2.0.0 with JSMP, SystemJS, and TS Loader in an ASP.NET MVC 5 (non-core) application. Encountering errors in Visual Studio related to locating angular modules. Severity Code Description Project File Line Suppr ...

Dealing with the 'UNIFIED_TEST_PLATFORM' issue while trying to compile an Ionic android app that utilizes tesseract.js and capacitor core

I recently set up an Ionic Angular project and integrated Capacitor to access native code functionalities. My project utilizes tesseract.js, as well as Capacitor core and camera plugins. However, I encountered an error while building the Android project: ...

Chrome autocomplete behaves as if the input fields are disabled and cannot be clicked on

I am experiencing an unusual issue with autofill in Chrome. After logging in and then logging out of the app, the input fields (email, password) are auto-filled but appear to be frozen and unclickable. This problem does not occur every time; it only happe ...

Typescript's identification of a dispute between RequireJS and NodeJS definitions

I obtained the Typescript RequireJS definition from Definitely Typed. It includes an ambient declaration of Require that clashes with the NodeJs command "require". See below for the declaration and the error message: Declaration: declare var require: Req ...

TypeORM ensures that sensitive information, such as passwords, is never returned from the database when retrieving a user

I developed a REST API using NestJs and TypeORM, focusing on my user entity: @Entity('User') export class User extends BaseEntity { @PrimaryGeneratedColumn() public id: number; @Column({ unique: true }) public username: string; publi ...

The absence of the 'profileStore' property is noticed in the '{}' type, which is necessary in the 'Readonly<AppProps>' type according to TypeScript error code ts(2741)

I'm currently using MobX React with TypeScript Why am I getting an error with <MainNote/>? Do I just need to set default props? https://i.stack.imgur.com/5L5bq.png The error message states: Property 'profileStore' is missing in typ ...

Tips for incorporating auth0 into a vue application with typescript

Being a beginner in TypeScript, I've successfully integrated Auth0 with JavaScript thanks to their provided sample code. However, I'm struggling to find any sample applications for using Vue with TypeScript. Any recommendations or resources would ...

Error encountered in ngtsc(2345) where an argument of type 'Event' is being used instead of an expected parameter type of 'SortEvent'

I recently started using angular and encountered an issue while trying to sort columns. The error message I received was: Argument of type 'Event' is not assignable to parameter of type 'SortEvent'. Type 'Event' is missing t ...

Creating a new TypeScript file via the command line: A step-by-step guide!

When I want to create a new file named main.ts, I try to write the command but it keeps showing an error. "bash: code: command not found" https://i.stack.imgur.com/cpDy3.png ...

The functionality of the Protractor right click feature is smooth, however, there seems to be an issue with selecting

Even though I can locate the button within the context menu, I am facing difficulty in clicking it. The code mentioned below is successfully able to click the button, but an error message pops up indicating: Failed: script timeout (Session info: chr ...

Having trouble manipulating text or values of angular elements with Selenium and Python

https://i.stack.imgur.com/vZdo0.png I am facing an issue with a date input field that does not have a calendar or dropdown for selection. I tried using driver.find_element_by_id('dataInicio').send_keys(date_value) but it doesn't seem to work ...

Steps for wrapping a class with a higher order component

Is it feasible to encapsulate a class component within a higher order component (HOC) that is also a class? import React, { Component } from "react"; import { View } from "react-native"; import { Toast } from "react-native-easy-toast"; const withToast = ...

Typing in Angular's decimal pipe results in inaccurate rounding up

Utilizing the decimal pipe from Angular, here is an example: <input pInputText type="number" [ngModel]="factor | number: '.2'" (ngModelChange)="factor=$event"> Upon loading my page, it correctly displays factor as 50.00 which is set in my ...

Assign a value to a variable using a function in Typescript

Is there a way in typescript to explicitly indicate that a function is responsible for assigning value to a variable? UPDATED CODE Here, the code has been simplified. While getText() ensures that it will never be undefined, this may not hold true in subs ...

What causes the NavBar to show and hide within a specific range?

Recently, I encountered a perplexing issue with my navbar. It functions correctly except for one strange behavior that has left me baffled. Why does the menu appear when I adjust the width to 631px, but disappear at 600px? And vice versa – why does it wo ...

Upon completion of a promise in an express middleware and breaking out of a loop, a 404 error is returned

In my efforts to retrieve an array of object (car) from express using database functions in conjunction with the stolenCarDb object, everything seems to be working fine. However, when attempting the following code snippet, it results in a 404 error w ...

How do I add a new module to an existing one using Angular-CLI?

After generating modules: $ ng generate module myTestModule installing module create src/app/my-test-module/my-test-module.module.ts $ ng generate module myTestModule2 installing module create src/app/my-test-module2/my-test-module2.module.ts I ha ...

Definition files (.d.ts) for JavaScript modules

I'm currently working on creating Typescript typings for the link2aws package in order to incorporate it into my Angular project. Despite generating a .d.ts file, I am still encountering the following error message: TypeError: (new link2aws__WEBPACK_I ...

Creating a generic component map resolver for flexible applications

Currently, I am engaged in a project where the backend allows for the modeling of dynamic content that is later displayed as Components on the frontend. Everything seems to be functioning well, except when dealing with models where the dynamic content con ...

Oops, it seems like there was an issue with NextJS 13 Error. The createContext functionality can only be used in Client Components. To resolve this, simply add the "use client" directive at the

**Issue: The error states that createContext only works in Client Components and suggests adding the "use client" directive at the top of the file to resolve it. Can you explain why this error is occurring? // layout.tsx import Layout from "./componen ...