Angular - Monitoring Changes in Variables

I've recently started working with Angular, primarily using VueJS. I'm curious about how to detect when a variable is updated. In my case, the variable is being updated through a DataService. I came across ngOnChanges(), but it seems that it only works for inputs.

Here's an overview of my code:

import { DataService } from "../../service/my.service";

export class MainPage {
  myVar: String = ""; // this is the variable I want to monitor for changes

   constructor (
    private data: DataService
   ) {}

   ngOnInit() {
    this.data.changeVar.subscribe(message => this.myVar = message);
  }
}

my.service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject<string>("");
  changeVar = this.messageSource.asObservable();

  constructor() { }

  changeMyVar (message: string) {
    this.messageSource.next(message)
  }

}

This is where I update the variable.

import { DataService } from "../../service/my.service";

export class AnotherPage {
  anotherVar: String = '';

  constructor(
    private data: DataService
  ) { }

  ngOnInit() {
    this.data.changeVar.subscribe(message => this.anotherVar = message)
  }

  myFunction () {
    this.data.changeMyVar("Hello"); // update variable to "Hello"
  }
}

Any assistance would be highly appreciated! :)

Answer №1

If you want to handle changes in the variable myVar only within the Observable callback defined in the method ngOnInit, you can implement a method that gets called after the variable is updated:

export class MainPage {

    myVar: string = "";

    ngOnInit() {
        this.data.changeVar.subscribe(message => {
            if (message !== this.myVar) {
                this.myVar = message;
                this.doSomething();
            }
        });
    }

    private doSomething() {
        ...
    }
}

Alternatively, if myVar needs to be accessible and potentially modified from other parts of the code (since it is public), you can use a getter and setter method to access it and trigger the action method in the setter:

export class MainPage {

    private _myVar: string = "";

    get myVar(): string {
        return this._myVar;
    }
    set myVar(value: string) {
        if (value !== this._myVar) {
            this._myVar = value;
            this.doSomething();
        }
    }

    ngOnInit() {
        this.data.changeVar.subscribe(message => this.myVar = message);
    }

    private doSomething() {
        ...
    }
}

Answer №2

Here is a helpful tip for you: https://angular.io/api/core/OnChanges

To access the changes of an object, you can use: changes.objectName

For further information, visit the angular.io page.

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

How can esbuild be used to load .wglsl files in Typescript files?

I'm currently utilizing esbuild to bundle my Typescript code, but I'm facing a challenge with configuring a loader for ".wgsl" files. Here is my app.ts file: import shader from './shader.wgsl'; //webgpu logic This is my shader.d.ts fi ...

Prevent display of host attributes in Angular 2

My Angular component features a title property. // Here is the code snippet for the component: @Input('title') public title: string // This is how you can use the component in your code: <dialog [title]="bar"></foo> However, when t ...

Approaches to evoke input onchange in Angular spec

How can I trigger the <input type="file"> onChange method in order to unit test the handleFileSelect function? When attempting to do so, I receive an error stating "imageInputNE.onchange is not a function". Here is the spec that I have written: ...

When executing the release command in Ionic 3, the Angular AoT build encountered a failure

Struggling to get my Sony Z2 smartphone app running. Command used: ionic build android --prod --release Error displayed in console: typescript error Type CirckelmovementPage in C:/Users/fearcoder/Documents/natuurkundeformules/src/pages/cir ...

Creating a key-constrained type in Typescript for object literals with automatically deduced number values

Suppose we have an object literal defined as: export const SOURCE = { UNKNOWN: 'Unknown', WEB: 'Web', MOBILE: 'Mobile', ... } as const; and export const OTHER_SOURCE = { UNKNOWN: 0, WEB: 1, MOBILE: ...

npm ERROR! Encountered an unexpected symbol < within the JSON data at position 12842

I keep encountering an error every time I attempt to install a package or run npm install. Despite my limited experience with Angular 4, having only started using it a week ago, I am puzzled by this error. Any guidance on how to resolve it would be greatly ...

Incorporating DefinitelyTyped files into an Angular 2 project: A step-by-step guide

I am currently developing an application using angular 2 and node.js. My current task involves installing typings for the project. In the past, when starting the server and activating the TypeScript compiler, I would encounter a log with various errors rel ...

There was an issue encountered while compiling the template for 'AppModule'

While attempting to construct an Angular 6 application, I encountered an issue when utilizing the --prod flag. ERROR in Error during template compile of 'AppModule' Expression form not supported in 'reducers' 'reducers' ...

Incorporate a module that was developed locally into your project

Attempting to incorporate a locally developed Angular project/module into an angular application without having to publish it on the npm repository has been quite a challenge for me. To begin with, I decided to follow a tutorial that guided me through bui ...

Verify web connectivity in an Angular2 (non-Ionic) Cordova application

Our team has developed an Angular2 Cordova application (not Ionic) that interacts with multiple backend services. We want the app to display a specific page (Component) if a user is offline. Although we have already created this feature, we are unsure of ...

What is the best way to define multiple variables in ionic 2 using Angular2 and TypeScript?

I'm brand new to working with ionic2/Angular2/Typescript. My project involves creating a wheel with eight slices, but I'm struggling with how to declare multiple variables. In JavaScript, I've declared them like this: function rand(min, max ...

Using a custom TypeScript wrapper for Next.js GetServerSideProps

I developed a wrapper for the SSR function GetServerSideProps to minimize redundancy. However, I am facing challenges in correctly typing it with TypeScript. Here is the wrapper: type WithSessionType = <T extends {}>( callback: GetServerSideProps&l ...

Generating auto UUIDs in PostgreSQL using TypeORM

Currently, I am in the process of developing a REST API and utilizing TypeORM for data access. While I have been able to use it successfully so far, I am facing an issue regarding setting up a UUID auto-generated primary key on one of my tables. If anyone ...

Using Angular 2 to assign a function to the ngClass directive within the template

I've been searching for a solution to this issue, but so far nothing has worked for me. When I try to pass a function to the ngStyle directive, I encounter the following error: The expression 'getClass()' in ProductView has changed after i ...

Tips for preventing the need to convert dates to strings when receiving an object from a web API

I am facing an issue with a class: export class TestClass { paymentDate: Date; } Whenever I retrieve an object of this class from a server API, the paymentDate field comes as a string instead of a Date object. This prevents me from calling the ...

How can I reference MyClass.new as a method in Typescript?

Within my code, I have an array of objects and each object is structured like this: { id: 'string', name: 'string' } There's a class defined as follows: class User { constructor(obj: Record<string, string>) { Object.as ...

A guide to sorting through in-app notifications in REACT-NATIVE based on their read status

Incorporating two headings, "Unread" and "Read", into the notification system is my goal. When opened, the Unread Notifications should be displayed beneath the Read notifications. This data is being retrieved from an API. Each notification contains a key ...

Storing multiple items in an array using LocalForage

I have a challenge where I need to add multiple items to an array without overriding them. My initial approach was like this: localForage.getItem("data", (err, results) => { console.log('results', results) // var dataArray ...

To determine if two constant objects share identical structures in TypeScript, you can compare their properties

There are two theme objects available: const lightMode = { background: "white", text: { primary: "dark", secondary: "darkgrey" }, } as const const darkMode = { background: "black", text: { prim ...

"Setting Up a Service in Angular: A Step-by-Step Guide

I am facing an issue with a root service that contains composition within it, as shown below: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class MapService { private rmap: RMap; ini ...