How can we identify when the value of a class instance is updated in Angular 4?

I have a Maths class that allows me to alter the operation type.

export class Maths {
   private static _instance: Maths = new Maths();
   type: string = "ADD";

   constructor() {
     Maths._instance = this;
   }

   public static getInstance(): Maths {
     console.log("Instance Provided");
     return Maths._instance;
   }

   // update operation type method
   changeType(newType) {
     type = newType;
   }
}

In one of my components, I have an instance of the Maths class and I need to detect changes in this instance, but it's not working. Below is the code snippet:

import { Component } from '@angular/core';
import { Maths } from './Maths';

@Component({
  selector: 'operation-cmp',
  template: ''
})

export class OperationComponent {
  mathsType: Maths;
  constructor() {

     //Creating instance of Maths
     this.mathsType = Maths.getInstance();

     // Attempting to detect instance change
     if(this.mathsType.type == "MULTIPLY") {
        //Do something here
     }
}

My app component updates the type of the Maths class on button click as shown below:

import { Component } from '@angular/core';
import { Maths } from './Maths';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

 maths;
 type = "MULTIPLY"

 constructor() {

 }

 // This function is called on button click
 changeType() {
  this.maths = Maths.getInstance()
  this.maths.changeType(type);
 }
}

I am unsure how to detect changes in the Maths class's instance value in the OperationComponent. I need to perform certain actions based on the type within the OperationComponent.

Please assist me in finding a solution.

Answer №1

If you want to handle notifications in your application, consider using the Subject type. Create an instance of Subject within the Maths class and trigger notifications from it when the changeType function is called.

export class Maths {
   private static _instance: Maths = new Maths();
   private typeChange: Subject = new Subject();
   type: string = "ADD";

   constructor() {
     Maths._instance = this;
   }

   public static getInstance(): Maths {
     console.log("Instance Provided");
     return Maths._instance;
   }

   public changeType(newType) {
     this.type = newType;
     this.typeChange.next(); // Add notification to container
   }

   public onTypeChange() : Subject {
      return this.typeChange;
   }
}

In the OperationComponent, access the subject and subscribe to it.

export class OperationComponent implements OnInit {

  mathsType: Maths;

  constructor() {
     this.mathsType = Maths.getInstance();
  }

  ngOnInit() {
     this.mathsType.onTypeChange().subscribe(data => /*Implement your logic here*/)
  }

}

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

Unexpected outcomes when using three.js getWorldPosition method

Please check out the gist I put together over at https://gist.github.com/sparkbuzz/f1f8d0d8bbc7757b679f In this gist, you'll find a TypeScript class named OrbitControls. I've been delving into 3D and three.js to explore creating orbit-style con ...

Advancing Components in Angular 2

As I try to develop a component that extends from another component, I find that my code is becoming cluttered with the need to pass constructor parameters down to child components. Is there a more efficient way to organize this code structure? The base c ...

Is there a way to monitor user engagement within my app without depending on external analytics platforms?

I'm looking to enhance the user-friendliness of my applications deployed on the Play Store by tracking users' interactions. Specifically, I want to keep track of: Screen Time: Monitoring how much time users spend on each screen. Clicks: Tracking ...

The styling of Primeng Carousel appears to be incorrect

After obtaining a copy of the Primeng v8 carousel component, I noticed that the output is quite different from what is displayed on its official website: <p-carousel dir="ltr" [value]="basicDataService.latestProducts" [numVisible]="4"> <ng-t ...

Failed to compile Angular project - Module is missing

I attempted to launch an Angular project, but encountered failure. Upon running "ng serve --open" in my project, the following information was displayed: ** Angular Live Development Server is listening on localhost:4200, open your browser on http://localh ...

Null errors are encountered when working with Angular 4 Reactive Forms FormControl

When navigating through the text inputs without providing any input, the error message divs are displayed to indicate that the required validator is functioning correctly. However, if I enter anything into one of the fields, an error is immediately thrown ...

Access custom IDs in Angular FormArrays to retrieve specific FormControls

I'm having trouble setting the formControlName of a formArray and connecting it to an input field. Form: this.translationForm = new FormGroup({ translations: new FormArray([]), }); this.translations.push( new FormControl({ de: '' }, [ ...

Updating ng-bootstrap to be compatible with Bootstrap 3.3.7 by downgrading from version 4.3.1

I have an Angular 6 project with Bootstrap 4 and ng-bootstrap for modal dialogs. However, I need to integrate this into another project which is using Angular 3.3.7. As a result, I was required to downgrade the version of Bootstrap. Here are the steps I fo ...

Enhancing State Management with CombineReducers in TypeScript

export const rootReducer = combineReducers({ login: loginReducer, }); Everything is working fine with the current setup, but I encountered an issue when attempting to combine another reducer: export const rootReducer = combineReducers({ login: lo ...

Angular - Evaluating the differences between the object model and the original model value within the view

To enable a button only when the values of the 'invoice' model differ from those of the initial model, 'initModel', I am trying to detect changes in the properties of the 'invoice' model. This comparison needs to happen in th ...

Typescript integration with Sequelize CLI for efficient database migrations

According to the Sequelize documentation, it claims to work with Typescript. However, for it to be fully functional in a production environment, DB migration scripts are necessary. The issue arises when using the Sequelize CLI as it only generates and runs ...

Introducing the Eventbridge Pipeline enhancer: a tool that assigns a personalized MessageGroupID to each message without

My setup involves an SQS queue that is connected to a FIFO queue through an eventbridge pipe. The pipe extracts a value from the payload and assigns it to the MessageGroupID using a JSONpath expression. import { SqsTarget } from '@aws-cdk/aws-pipes-ta ...

Linking a group of child checkboxes to a single parent

Is there a way to link multiple checkboxes from various child elements to one parent element (e.g. using a model)? Imagine that each child component includes something like: <input type="checkbox" :id="'ticket-'+id" ...

Combining the values of two input fields in Angular

Within my form, I have three input fields labeled Name, hours, and minutes. When I execute a POST operation, I combine the values of hours and minutes into a variable named duration before sending it to the api. The resulting JSON structure appears as fo ...

Capture and handle JavaScript errors within iframes specified with the srcDoc attribute

My current project involves creating a React component that can render any HTML/JavaScript content within an iframe using the srcDoc attribute. The challenge I am facing is implementing an error handling system to display a message instead of the iframe ...

Having trouble uploading big files on your Windows system?

My challenge is to successfully upload a large file using Angular. Specifically, I am attempting to upload a Human Genome tar file, which is a minimum of 2.5gb in size. Strangely, when I try to upload the file from Linux using any browser such as Chrome or ...

What methods can be used to deduce the data types of properties buried within multiple

I am currently developing a function that receives a descriptor object and leverages the inferred type information to generate another object with a user-friendly API and strong typing. One issue I have encountered is that TypeScript only infers the types ...

Ways to remove redundant code from multiple service calls

Within my DataService, I have set up an observable for various API calls. I am looking to streamline the process by creating a reusable block of code to be used in each HTTP request. export class DataService { constructor( private http: HttpClient, ...

What is the best way to provide data types for Vuex mapState functions?

In my Vuex component using Typescript, I want to add types to the mapping functions in mapState. Previously, I had it set up like this: @Component({ computed: { ...mapState( MY_NAMESPACE, { fooIndex: ( state: MyModel ) => state.values.index ...

Unlock the tab element within a modal using ng-bootstrap

I am currently encountering an issue with ng-bootstrap in Angular 2. I am unable to access the #tabs variable from my component using @ViewChild. This problem arises only when I utilize the tab directive within the modal directive. Here is a snippet of m ...