Enhancing the Value of BehaviorSubject with Object Assign in Angular using Typescript and RxJs

I have a user object stored as a BehaviorSubject which is being observed. I need help figuring out how to detect if a specific value within my user object has changed.

I've noticed that my current implementation doesn't seem to work correctly, and I suspect it's because of how I update the user object. It seems like I may be overwriting both the old and new values in the BehaviorSubject, resulting in always comparing the same object?

export interface User {
   id: string;
   username: string;
   isBanned: boolean;
   subscription?: UserSubscription;
}

export class AuthService {
  public readonly user$: Observable<User| undefined> = this.user.asObservable();
  user: BehaviorSubject<User| undefined> = new BehaviorSubject<User| undefined>(undefined);

  updateUserSubscription(newUserSubscription: UserSubscription): void {
    // Here I simply want to update the subscription-Object of my user
    this.user.next(Object.assign(this.user.value, newUserSubscription));
  }
}

export class MemberService {
  user?: User;
  private subscription?: Subscription;

  constructor(public auth: AuthService) {
     // Here I simply want to detect subscription changes
     this.subscription = this.auth.user$.pipe(
        pairwise(),
        filter(users => this.detectSubscriptionChange(users[0], users[1]))
     ).subscribe(([user1, user2] => { // some code ... })
   }

  detectSubscriptionChange(user1: User | undefined, user2: User | undefined): boolean {
      //subscription status is always the same, as the objects are always the same...
      return user1?.subscription?.status !== user2?.subscription?.status;
  }

}

Is there a better way for me to update the values in my user object so that I can accurately compare them in the observable?

Thank you!

Answer №1

To create a clone using Object.assign(), start by passing an empty object {} as the first parameter, and then assign the user object to that new empty object, creating a new user clone.

const user = Object.assign({}, this.user.value);

Currently, you are simply assigning the subscription object to the current user.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

In more recent versions of JS / Typescript, the spread operator provides a cleaner way to clone objects, similar to what you might expect from Object.assign():

const user = {...this.user.value});

If I understand correctly how your User and UserSubscription models are set up, you may also need to directly update the subscription value like this:

user.subscription = newUserSubscription
this.user.next(user);

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

I built a custom Angular application integrated with Firebase, and I'm looking for a way to allow every user to have their individual table for managing tasks

I am looking to enhance my code so that each user who is logged in has their own tasks table, which they can update and delete. Additionally, I need guidance on how to hide menu items tasks, add-tasks, logout for users who are not logged in, and display th ...

Angular is unable to display Observable userdataof any type in an asynchronous task

My home component's HTML is not displaying my userData: <h1 class="display-4">Hello, {{ (userData | async)?.username }}</h1> This is the call in home.component.ts: ngOnInit(): void { this.userData = this.userService.getUser(); } ...

What steps do I need to take in order to create a histogram with perfect symmetry?

I am looking to create a unique JavaScript program that can generate a symmetric histogram resembling the image provided below: This program will prompt the user to input the number of bars they want to display and specify the character used to draw the b ...

Looking to implement pyperclip functionality on Heroku platform

Is it feasible to utilize pyperclip on Heroku with a Selenium application in order to copy something to the clipboard? Since the platform utilizes a 'headless' browser and lacks a GUI, accessing the clipboard is challenging. Is there any way for ...

Issue with Angular 6 and Html Webpack Plugin

My project was recently updated from Angular 5 to Angular 6, causing some changes in the file structure. The webpack.config files are no longer present and the project now operates under CLI engage. However, I encountered an issue after the migration rela ...

Are you transitioning from traditional scroll pagination to using ajax?

Is it possible to replace scroll pagination with ajax? I'm looking for an alternative to the large scroll pagination query and wondering if ajax could be used instead. Here is the current code snippet: feeds.scrollFeedPagination({ 'contentPage ...

Why does the API in Next Js get triggered multiple times instead of just once, even when the strict mode is set to false?

React Query Issue I am currently facing an issue with React Query where the API is being triggered multiple times instead of just once when the selectedAmc value changes. I have tried setting strict mode to false in next.config.js, but that didn't so ...

Discovering the category for ethereum, provider, and contract

My current interface looks like this: interface IWeb3 { ethereum?: MetaMaskInpageProvider; provider?: any; contract?: any; }; I was able to locate the type for ethereum using import { MetaMaskInpageProvider } from "@metamask/providers", ...

Receiving the most recent data in a protractor examination as a text string

My goal is to fetch an input value for a specific operation in protractor. I am attempting to make an ajax request using protractor and need to assign a unique value (referred to as groupCode) to a JSON object that will be sent to the server. Initially, I ...

Is there a way to match a string with information stored in a JSON file?

I have a snippet in my index.js that looks like this: if ('and' == trueWords) { console.log('Success!') } else { console.log('Failure!') } Below is the content of my json file: { "and": 1 } Appreciate your help! ...

Images in Next.js work properly in a local environment, but encounter issues in the production environment

My Next.js images are working fine on local, but when I try to push it to production, it crashes. Here is my code View my image component here This is where I map the images Here is the part of my .json file where I fetch data It works properly in loca ...

React Router v6 is throwing an error stating that within the <Routes> component, all children must be either a <Route> or <React.Fragment>

While the code snippet below may have worked perfectly fine in React Router v5, it's causing an error in React Router v6. Error: [Player] is not a <Route> component. All component children of <Routes> must be a <Route> or <React ...

Create a separate child process in Node.js

Is it possible to create a separate process from the current script? I want to execute another script while the original one is still running. This new script should be completely independent of the calling script. ...

Reinitializing the database with Cypress (postgresql)

When populating the database, I intentionally do it partially for certain tests. However, after completing all tests, I would like to reset the database in order to avoid any complications that may arise during the next populate process. How can I efficien ...

Encountering an uncaught SyntaxError due to an unexpected token < while working with AngularJS2 on a local

I am currently facing an issue while trying to run my angularjs2 project locally using nodejs. I can successfully run it using npm start but encountering errors when attempting to use node app.js. The error message that pops up states: "systemjs.config.js ...

What is the reason behind the success of 'as' in ngFor compared to '='?

<tr *ngFor = "let item of list; let i = index;"> An issue arises with the code above: The error message reads: Type 'number' is not assignable to type 'string'. td [ngModelGroup]="j" #temp="ngModelGroup ...

Issue with socket malfunctioning when integrated with express

I’m encountering an issue with the socket in my program. While I can easily broadcast from any part of the program using "io" connection, I face limitations when trying to use "socket" for broadcasting unless it is within the same connection as "io." I a ...

Unnecessarily intricate: A Comparison and Enumeration of Elements in Arrays

I am facing a challenge with organizing arrays that represent categories and subjects. Each array represents a category, while each item within the array is a subject. For example: 4 Categories with Subjects ['A','B','D'] [&a ...

Facing issues during the unit testing of an angular component method?

I'm facing an issue with a unit test that is failing. Below is the code for reference: Here is my typescript file: allData: any; constructor(@Inject(MAT_DIALOG_DATA) private data, private dialogRef: MatDialogRef<MyComponent>, priva ...

The ng-change event in AngularJS is not being activated by IE 11

Hello everyone, I am currently working with the angularjs framework and implementing a datepicker functionality. Unfortunately, the input type date is not functioning correctly on Internet Explorer. As a workaround, I have utilized jquery and css to create ...