Exploring Angular 12: Techniques for Monitoring Property Changes in a Service

Within my current project, there exists a series of dependencies. Specifically, there is a shared service class containing an object named "myObject" which many components access and modify. The issue at hand is that each component is independently modifying the values of "myObject" and saving these changes to the server.

A recent requirement has surfaced to centralize the saving process. The goal is for a centralized mechanism to automatically save the values of "SharedService.myObject" whenever they are altered.

export class SharedService {
   myObject: MyClass;
}

// This interface is generated by an API
export interface MyClass {
   id?: number;
   someArray?: Array<SomeOtherInterface>;
   someOtherObject: SomeOtherInterface;
}

I attempted a solution using getters and setters, but it seems the setter is not triggered when the values of "myObject" change.

export class SharedService {
   _myObject: MyClass;
   get myObject() {
     console.log('tracking changes' + JSON.stringify(this._myObject));
   }

   // Setter is not being called upon any change in myObject
   set myObject(myObject: MyClass) {
     console.log('Values changed pre -> ' + JSON.stringify(this._myObject));
     console.log('Values changed new -> ' + JSON.stringify(this.myObject));
   }
}

I am seeking a solution to track changes within the SharedService itself, without needing to modify all existing components. Is there a way to achieve this?

Answer №1

If you implement this approach. In Your application :

export class SharedService {
   _myObject: MyClass;
   get myObject(): MyClass {
     console.log('tracking changes' + JSON.stringify(this._myObject));
return this._myObject

   }

   // The setter is not triggered when there is a change in myObject
   set myObject(newState: MyClass) {
     console.log('Values changed before -> ' + JSON.stringify(this._myObject));
     console.log('Values changed after -> ' + JSON.stringify(this.myObject));
//new lines
this._myObject = {...this._myObject,...newState}

   }
}

Let's say you need to update the someArray data within a class that has an instance of this service:

let someArray = [1,2,3,4,5,6]
let newState : MyClass = {someArray};
//(commit) your new State
this.sharedService.myObject = newState;

// If there is a template that depends on this state, it will dynamically change.

// For example, all your template variables should rely on the state reference.

Assume you are using the ngFor directive with someArray as an array

get someArray(){return sharedService.myObject.someArray }

The get function is a computed function that only runs when there is a new update;

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

Encountering Issues with TypeScript Strict in Visual Studio Code Problems Panel

I have discovered that I can optimize my TypeScript compilation process by utilizing the --strict flag, which enhances type checking and more. Typically, I compile my TypeScript code directly from Visual Studio Code with a specific task that displays the c ...

Sharing an Angular 2 class instance across components

As a beginner with Angular 2, I'm adapting well so far. However, I've encountered a problem (possibly due to my familiarity with Angular 1) - I need the class "User" to be global and accessible across different components. Currently, I have a Us ...

Sending information to a service from the main.ts file in an Angular application

Within my Angular CLI application, I have a main.ts file that includes the following export statement. This file serves as a microservice that receives CONTEXT from another microservice. export default { async mount({ rootElement, context }: Extension) ...

fa-icon generates an error when a properly formatted closing tag is entered

Currently, I am developing an Angular application which includes a small component for listing files. I am in the process of adding icons for editing one of the fields in this component. However, I am facing an issue with the fa-icon component. I have two ...

Dealing with DomSanitizer problem in Angular 2

When using background-image inline for my *ngFor list items, I encountered an issue. In my Component Class, I defined a variable to store a common part of the images' URLs (e.g., ) along with unique parts of the image URLs as this.image (such as qwer ...

I am searching for a way to retrieve the event type of a svelte on:input event in TypeScript, but unfortunately, I am unable to locate it

In my Svelte input field, I have the following code: <input {type} {placeholder} on:input={(e) => emitChange(e)} class="pl-2 w-full h-full bg-sand border border-midnight dark:bg-midnight" /> This input triggers the fo ...

What is the correct way to add type annotations to an Axios request?

I have meticulously added type annotations to all endpoints in my API using the openapi-typescript package. Now, I am looking to apply these annotations to my Axios requests as well. Here is a snippet of code from a Vue.js project I have been developing: ...

How can I implement password autofill feature on iOS using Ionic 4 and Capacitor?

I recently developed an app on the Apple Store using Ionic 4 & Capacitor. However, I am facing issues with saving the ID and password during the first login and updating it later. I have tried: Adding an Associated Domain file to the domain (https://dev ...

An informative step-by-step approach to constructing Angular applications utilizing npm and TypeScript

When I first encountered Angular2, I was introduced to TypeScript, npm, and more for the very first time. I was amazed by their power, but I know I've only scratched the surface. While I can navigate through the "development mode," my ultimate goal i ...

Can you guide me on incorporating a date input with ngModel?

I have a date input field set up as follows: <input [(ngModel)]="value" type="text" class="form-control"> Can someone explain how I can display and submit the value correctly? The user's input should be formatted as dd/MM/yyyy, while t ...

Guide on showcasing the parameter passed in a TypeScript file on an HTML page

Just starting out with the Ionic framework and I'm attempting to show the parameter passed from the home page on my new page. I've gone through the code below but so far, nothing is showing up. Any ideas on what might be missing? Thanks in advan ...

Using custom properties from the Material-UI theme object with custom props in Emotion styled components: a step-by-step guide

I have implemented a custom object called fTokens into the MUI theme using Module augmentation in TypeScript This is how my theme.d.ts file is structured declare module "@mui/material/styles" { interface FPalette { ... } interface FTokens ...

What is the proper way to utilize a class with conditional export within the Angular app.module?

This query marks the initiation of the narrative for those seeking a deeper understanding. In an attempt to incorporate this class into app.module: import { Injectable } from '@angular/core'; import { KeycloakService } from 'keycloak-angul ...

Notify the user with a message that our support is limited to Chrome, Firefox, and Edge browsers when utilizing Angular

How can I display a message stating that we only support Chrome, Safari, Firefox, and Edge browsers conditionally for users accessing our site from other browsers like Opera using Angular 10? Does anyone have a code snippet to help me achieve this? I atte ...

What is the process for personalizing the appearance in cdk drag and drop mode?

I have created a small list of characters that are draggable using Cdk Drag Drop. Everything is working well so far! Now, I want to customize the style of the draggable items. I came across .cdk-drag-preview class for styling, which also includes box-shado ...

Sending information to a personalized mat-grid element using properties

I am currently working on enhancing the functionality of the angular material mat-tree component by building a custom component. The main objective is to create a table with expandable and collapsible rows in a hierarchical structure. I have managed to ach ...

How can you modify the height of the header field in Grid?

I have a single grid-tile: <md-grid-tile class="header"> <md-card class="content"> <md-card-header> <md-card-title>Monday</md-card-title> <md-card-subtitle>29.03.17</md-card-subtitle> ...

Embed a React component within an Angular 6 application

I am attempting to integrate a React component into an Angular 6 project. The React component I am using is from the tic-tac-toe tutorial which can be found at this link. Prior to adding the React component, my Angular host component was functioning corre ...

Real-time monitoring within a callback function in Angular 5

I need to ensure that a specific callback is executed only after receiving a response, starting from the line this.groupDefaultExpanded = -1; onwards. loadLoginDetails() { this.derivativeSpecService.getDerivativeDetails().subscribe( res => ...

typescript api overlooking the async await functionality

My controller contains an asynchronous method that is supposed to set a results object. However, I'm facing an issue where instead of waiting for the 'await' to finish executing, the code jumps to the response object call prematurely, leavin ...