What is the method for retrieving the current value of a BehaviorSubject just once?

I am attempting to retrieve the current value of a BehaviorSubject without directly subscribing to it in order to avoid real-time changes reflecting immediately due to a specific requirement. My approach involves using the getValue() method.

Here is an example of the BehaviorSubject value:

{
  ID_123: {
     logs: [ 
       {
         id: 1,
         record_id: 'ID_123',
         data: { complete: false }
         action: 'Modified',
         description: 'Modified filename',
       }
     ]
  }
}

This is how my Service class looks like:

private logs$ = new BehaviorSubject<any>(null);
private logsDataStore = {};
logsData = this.logs$.asObservable();

...

getData(id) {
   if (this.logsDataStore[id] !== undefined) {
       return this.logs$.getValue();
   }
}

I invoke the getData() method from within a component upon clicking a button to display the logs entries.

id = 'ID_123';

onClick() {
   this.logsData = Object.assign({}, this.service.getData([this.id])[this.id]);
}

Displaying each entry in the logs:

<div *ngFor="let log of logsData.logs" class="log">
   <a *ngIf="!log.data.complete" (click)="markComplete(log.record_id, log.id, log.data)">
     Mark Complete
   </a>
</div>
markComplete(recordId, id, data) {
   let dataClone = Object.assign({}, data);
   dataClone.complete = true;
   this.service.updateLog(recordId, id, dataClone);
}

Returning back to the Service class:

updateLog(recordId: string, id: string, newValues: object) {
    const selectedRecord = this.logsDataStore[recordId];
    if (selectedRecord !== undefined) {
      if (selectedRecord.logs && selectedRecord.logs[id]) {
        let selectedLogEntry = selectedRecord.logs[id];
        Object.keys(newValues).forEach(
          (logKey) => {
            selectedLogEntry[logKey] = newValues[logKey];
          }
        );
      }
    }

    // this.logs$.next(Object.assign({}, this.logsDataStore));
  }

The issue:

Upon clicking the Mark Complete link, it disappears instantly, even though I made sure not to subscribe directly to the service and created a clone of the results retrieved from getData(). Is there something crucial that I am overlooking?

Any insights would be greatly appreciated.

Answer №1

I stumbled upon a new revelation.

After experimenting with:

JSON.parse(JSON.stringify(this.service.getData([this.id])[this.id]));

Success!

Until now, I had assumed that Object.assign() and JSON.parse(JSON.stringify()) functioned in the same manner. However, it turns out that JSON.parse(JSON.stringify()) is the one that actually generates a deep copy, preserving the original object without reference.

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

Utilizing camera perspective for coordinate system in Three.js

This question may seem basic, but I'm having trouble grasping it. I'm working on a scene using Three.js and the camera setup is as follows: var camera = new THREE.PerspectiveCamera( 85, window.innerWidth/window.innerHeight, 0.1, 1000 ); camera. ...

value displayed - real-time editor

Recently, I added in-place editing feature to one of my models to enhance user experience. Among the attributes of the model, there is one called PRICE, for which I utilized the to_currency method to format the value properly before displaying it. Howeve ...

Is there a more efficient method in Typescript to define the types of an object containing arrays?

Suppose I have an object that contains various roles, each granting a specific set of rights: const allRoles = { user: [ 'right1' ], admin: [ 'right1', 'right2' ], } as const If I want to define the types ...

My React App is not displaying the expected Fetch API result

I'm encountering an issue with my react app where I'm trying to fetch an API. Here's the code snippet: import { useEffect, useState } from 'react' export default function Home() { let [ quote, setQuote ] = useState(null) us ...

The ability to drag the Google Maps marker is lost when a custom place is set using Autocomplete

I am currently working on developing a Custom Google Map that allows the user to select a position either through input with autocomplete suggestions or by dragging the marker on the map. Interestingly, I have noticed that when I create a map without the ...

The script is not functioning properly due to an error stating "(Uncaught ReferenceError: $ajaxUtils is not defined)"

I'm having trouble figuring out what the issue is (Uncaught ReferenceError: $ajaxUtils is not defined) document.addEventListener("DOMContentLoaded", function (event) { showLoading("#main-content"); $ajaxUtils.sendGetReque ...

Utilizing Material UI and TypeScript to effectively pass custom properties to styled components

Currently, I am utilizing TypeScript(v4.2.3) along with Material UI(v4.11.3), and my objective is to pass custom props to the styled component. import React from 'react'; import { IconButton, styled, } from '@material-ui/core'; con ...

Async/Await moves on to the next function without waiting for the previous function to finish executing

I am developing a web application that requires querying my database multiple times. Each query depends on the data retrieved from the previous one, so I need to ensure each call completes before moving on to the next. I have attempted using async/await fo ...

Incorporate the select2 plugin into your AngularJS project for enhanced functionality

In my AngularJS application, I am utilizing the select2 plugin to showcase a list of entities (tags). This snippet shows part of my template: select.ddlTags(ui-select2="select2Options", multiple, ng-model="link.tags") option(ng-repeat="tag in tags", ...

Changing the element tag and flipping escape characters in html entities

My control over the string source is limited, as I can only use html(). However, I am in need of cleaning up the chaos within the source, The goal is to remove all instances of <div class="page"></div>, while retaining its content. The challen ...

Tips for transferring data from a pop-up or modal window to the main window in ASP.NET MVC

Currently, I am in the process of developing a contact form within ASP.NET MVC. This contact form will allow users to easily attach regular files through traditional file and browse functions. Additionally, users will have the option to search for a specif ...

Display or conceal elements in a v-for select input by leveraging the value of another input with Vue3

In my form, I have two dropdown select option fields generated using loops from predefined constants. One dropdown is for selecting different "sides" and the other for choosing various "caps". When a user selects "2-Sided" in the sides dropdown, I want t ...

Encountered an issue with reading the property 'drop' from an undefined source during a straightforward migration

I recently started using the migrate-mongo library and encountered an issue during a simple migration process to create a view. Despite success in migrating up, I faced an error when attempting to migrate down. ERROR: Could not migrate down 20220620114132 ...

determine if the req.params parameter is void on an express route

Hi everyone, I'm a beginner with node and express and could really use some guidance. I am currently attempting to create a get request that checks if the req.params.address_line is empty, and then performs an action based on that condition. However, ...

recognizing individuals when a particular action is taken or when there is a disruption

Just starting to explore node.js I currently have a PHP/Laravel cms alongside a basic Nodejs game server that generates numbers in a loop To connect my PHP backend with Nodejs, I utilize Socketio and employ Socketio-JWT for user identification On the cl ...

Issue with Magento: Unable to execute dataflow profiles due to Ajax Error (Uncaught TypeError: e is not a function)

Whenever I try to execute a dataflow profile in Magento, the following series of events unfold: The CSV file is uploaded successfully X rows are found A message displays: Starting ... :: saveRow (handler-method) However, a JavaScript error interrupts th ...

Grab every piece of JavaScript code and styling from the HTML document and transfer it into a textarea field

Below is my code that extracts the JavaScript like this: src="assets/js/jquery.min.js" src="assets/smooth-scroll/smooth-scroll.js" I want it to look like this: (I believe my regex is incorrect): <script src="assets/js/jquery.min.js"></script> ...

transmitting user data to specified div container

Hey there, I have a question about sending user input to a div section in an HTML document. I've asked this before, but now I'm trying to be more specific. I'm having trouble getting the user input to display below each other in the div whe ...

Removing a Dynamic Element in ReactJS

--CustomFieldSection.js-- import React, { Component } from 'react'; import CustomField from './CustomField.js'; class CustomFieldSection extends Component{ constructor(props){ super(props); this.stat ...

Nested JSON array is being shown as [Object Object] within a TextField

I am facing an issue with mapping two sets of JSON data, which I will refer to as Set 1 and Set 2. In Set 1, the data (named sizingData) is being mapped to text fields using the following function: const fillTextField = () => { let result = []; ...