Behavior Subject in RxJS is able to emit a value even without explicitly calling the `next

I am in the process of developing a multi select filter using RxJs and an angular service to exchange values between various components.

@Injectable({
    providedIn: 'root'
  })
export class SomeService{

    private readonly defaulFilterSelect: SomeSelect[] = 
    [
      {
          id: 1,
          label: 'label 1',
          options: [
              { id: 2, isChecked: false},
              { id: 3, isChecked: false}
          ]
      },
      {
          id: 7,
          label: 'Label 2',
          type: { name: 'checkbox' },
          options: [
              { id: 4, isChecked: false},
              { id: 5, isChecked: false}
          ]
      }
    ]

    private filterSelectDataSource = new BehaviorSubject<SomeSelect[]>(this.defaulFilterSelect);

    filterSelectData$ = this.filterSelectDataSource.asObservable();

    public get getFilterSelectData(){
      return this.filterSelectDataSource.value;
    }
}

Now, here's the thing. As users interact with the application, they may change the property isChecked within the SomeSelect class to true, but then have the option to revert back to the initial state where all properties named "isChecked" are set to false. To achieve this, I had the idea that if I needed my observable to reset to its initial state, I could simply use the next() method with the default value defaulFilterSelect.

    uncheckAllOptions(){
      this.filterSelectDataSource.next(this.defaulFilterSelect); //here
  }

However, it seems that this approach is not producing the expected results. When I log the values in a subscribe function, I still see the previous value of my observable. Moreover, if I make changes directly to the object

this.filterSelectDataSource.value
without calling next(obj), the UI picks up on these changes and reflects them, which is puzzling to me. I would expect that only by calling
this.filterSelectDataSource.next(someNewObject);
should trigger UI updates based on the consumed observable.

Can anyone provide insights into the correct direction to resolve this issue? Thank you!

Answer №1

If you want to ensure that the initial value of filterSelectDataSource is independent from defaulFilterSelect, make sure to deep clone it. Otherwise, any updates made to one will affect the other due to them sharing the same reference.

There are various ways to deep clone objects, but personally, I often rely on Lodash's cloneDeep method for this purpose.

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

Angular: Changing the class of a parent element dynamically while iterating through a list with ngFor

I have a unique challenge where I am trying to style a checkbox as a button by placing it inside its label. <label> <input type="checkbox" name="..."> </label> My goal is to toggle the parent label's class based on whether the che ...

How to manually close the modal in Next.js using bootstrap 5

Incorporating Bootstrap 5.2 modals into my Next.js application has been smooth sailing so far. However, I've encountered an issue with closing the modal window after a successful backend request. To trigger the modal, I use the data-bs-toggle="modal" ...

Testing Angular 2 pipes with dependencies using angular-cli

I have been working on creating a test for a standalone Pipe. Currently, I am using the most recent version of angular-cli (including @angular 2.0.0). Here is the pipe code: import { Pipe, PipeTransform } from "@angular/core"; import { DatePipe, JsonPipe ...

The Material UI button shifts to a different row

I need help adjusting the spacing between text and a button on my webpage. Currently, they are too close to each other with no space in between. How can I add some space without causing the button to move to the next line? const useStyles = makeStyles((the ...

Scrolling through four limited list items automatically

Hey there! I am currently working on a design project. You can check it out here. I'm trying to replicate a section from another site, which you can see here. <div class="latest-winners-container"> <h3 class="header">Latest Winners< ...

How can one access this completely anonymous entity, and is there a way to identify it?

Similar Question: Understanding the Purpose of a Script Tag with src and Content While browsing through this webpage that explains how to include Google's +1 button, I came across an example code snippet that caught my attention: <script type ...

Is there a way to hide the tooltip displaying the most recent dates in Bootstrap?

After implementing a datepicker with bootstrap, I noticed that whenever I click on the field, it displays the last years I have selected. This behavior obstructs the calendar view and serves no real purpose. Below is an excerpt of my current script along ...

In Angular2, the derived class can inherit decorators

Within my Angular application, I am utilizing the BaseComponent which has a specified template. My goal is to use this same template HTML in a component that extends the base one. However, I am aware that class inheritance in Angular2 only applies to cla ...

The largest allowable call stack size within jQuery version 1.9.0

I have a question about poorly written code that I've been experimenting with. It's messy, but it's just for fun. I was attempting to create a "like system" where a user clicks on a button and the object ID associated with the button is sent ...

What is the best way to remove highlighted text from a textbox that is already selected?

So I have a JS function that I thought was simple, but I'm running into an issue. This function is supposed to select all the text in an ASP.NET textbox (input): function selectAllText(textbox) { textbox.focus(); textbox.select(); } I call t ...

JavaScript - Issue with For Loop when Finding Symmetric Difference

Here is my solution to a coding challenge on FreeCodeCamp called "Symmetric Difference." I'm puzzled as to why my code is returning 2, 3, 4, 6 instead of the expected 2, 3, 4, 6, 7. function sym(args) { args = Array.from(arguments); var new ...

Maintain user input within the table following a page refresh

I have been working on developing a table that allows users to edit it. I successfully created a script that adds comments to the table, but unfortunately, these comments disappear when the page is refreshed. I understand that I may need some additional to ...

The extent of utilizing the click handler in ECMA script 6

In ES6 arrow functions, the scope of this becomes available. However, there are instances where I cannot access this in an arrow function while it works with a normal anonymous function. For example: Sample 1 $(document).ready(function() { $(' ...

Utilizing Jquery or Javascript to Establish a Fresh Perspective for CylinderGeometry with Three.js

I'm attempting to change the dimensions of a cylinder created using examples from Three.js at runtime, but my code doesn't seem to be working. Here is the code snippet I am using: HTML <script src="http://www.html5canvastutorials.com/librari ...

what is the process for creating a dynamic display slide in bxslider?

I am trying to create a flexible length display using bxSlider. Here is the code I have so far. JS var duration = $('ul > li > img').data("bekleme"); $(document).ready(function () { $('.bxslider').bxSlider({ ...

Eliminating repeated keys from an array of objects

I'm dealing with an array of objects that looks like this let array = [ { sector: "adad" }, { sector: "adadasdsd" }, { sector: "sdsdsd" }, { origin: "sdfsf" }, { destination: "dfsfsdf" } ]; My goal is to trans ...

Creating a Mongoose Schema to store geoJson coordinates

I attempted to design a schema for geojson but ran into some issues with the syntax when handling coordinates. This is my current code: var DataSchema = new Schema({ properties: { title: { type: String, required: true }, description: { ty ...

Bootstrap table styling fails to be applied to dynamically generated tables via JavaScript

Hey there, I'm diving into the world of website development for the first time, just getting started a couple of days back. Although I have some experience with Python and C# programming, I'm facing challenges in generating an HTML table using J ...

Stylish elements within a higher-order component in a React application

Encountering two problems when using styled components within a higher order component wrapper in react. The component is being rendered without the specified background color. Encountering TypeScript errors with the ComponentWithAddedColors. Unable to id ...

Aligning the ant design carousel in the center of the page

I adjusted the size of an Ant Design carousel and now I want to position the image in the center of my screen. This is how the current image looks: https://i.sstatic.net/TmfDb.png Here is what I have attempted: const contentStyle = { heigh ...