Is there a way to track changes in a property on a service?

I'm searching for a way for components to receive notifications or subscribe to changes in a service variable.

Observables seem like an option, but I don't think they are suitable as they require completing the stream and I need continuous updates on the variable while the component is active.

Does anyone have a better suggestion for handling this scenario?

Answer №1

Have you ever experimented with Subject or any of its variations?

Here is an example using BehaviorSubject:

Service:

export class MyService {
  myVariableSubject = new BehaviorSubject<number>(0);

  increase() {
    this.myVariableSubject.next(this.myVariableSubject.value + 1);
  }
}

Component:

constructor(private myService: MyService) {}

ngOnInit() {
  this.myService.myVariableSubject.subscribe((value: number) => console.log(value));
}

Please be cautious as this may not be the optimal solution for your specific problem (which remains unspecified).

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

Applying a generic function to every property of an object in TypeScript to deduce the return value

I'm facing an issue with TypeScript where I need to solve a problem: type State = { alpha: string, beta: number } const selectors = { alpha: (s: State) => s.alpha, beta: (s: State) => s.beta } function createModifiedSelector< ...

How do React Native proxies differ from vanilla React proxies in their functionality?

Trying to retrieve data from an API running locally on port 5000 of my device, I recalled setting the proxy in package.json when working on React web applications: "proxy": "https://localhost:5000" Attempting to fetch information f ...

Is there a simple method I can use to transition my current react.js project to typescript?

I am currently working on a project using react.js and am considering converting it to typescript. I attempted following an article on how to make this conversion but have run into numerous bugs and issues. Is there a simpler method for doing this conver ...

How to position Angular Component at the bottom of the page

I have been working on my angular application and recently created a footer component that I want to stay at the bottom of the page like a typical footer. The footer component is included in the default app.component.html file, which makes it visible on th ...

Setting up roles and permissions for the admin user in Strapi v4 during the bootstrap process

This project is built using Typescript. To streamline the development process, all data needs to be bootstrapped in advance so that new team members working on the project do not have to manually insert data into the strapi admin panel. While inserting ne ...

Difficulty updating Angular packages using NCU (npm-check-update)

I attempted to update everything on my project by running the following commands: G:\Projects\salarkazazi> npm i -g npm-check-updates The output displayed the following warnings: npm WARN deprecated [email protected]: this library is n ...

Convert the XML response from an API into JSON

Is there a way to convert my XML response into JSON using Angular? This is the response I am working with: <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/"><?xml version="1.0" encoding="utf-8"?&gt; &lt;Fer ...

How to only disable checkboxes that are currently checked in Angular 8

click here to view an image**I would like to know how I can disable only the selected/checked items on a p-listbox in Angular 8. Is it possible to achieve this by adding a specific property or using CSS? Currently, when I try to add the [disabled] proper ...

The conundrum of nested function wrapping in Typescript and its impact on

Upon calling the following function, it returns a Promise<boolean>: const fnc = (i:number) : Promise<boolean> => Promise.resolve(true) // Promise<boolean> const res1 = errorHandler(errorPredicates.sdkError1, fnc, null, 4); However, ...

Unable to associate with 'href' because it is not recognized as a native attribute

As a newcomer to Angular 2, I have been following a beta course on Udemy. Now that I am looking to upgrade my project to the release candidate version, I am facing an error that seems unique and not mentioned anywhere online. In my main.ts file, the code ...

TS6059 found in excluded folder

I'm facing an issue with my tsconfig.json file that looks like this: {"compilerOptions": { "module": "commonjs", ...

Enhancing Typescript Arrow Function Parameters using Decorators

Can decorators be used on parameters within an arrow function at this time? For instance: const func: Function = (@Decorator param: any) => { ... } or class SomeClass { public classProp: Function = (@Decorator param: any) => { ... } } Neither W ...

Suggestions for projecting a polygon in openlayers using latitude and longitude data from a kml file?

As a beginner in openlayer mapping, I am struggling to display shapes such as points, polygons, and linestrings on my maps. While I have been able to show points successfully, I am having difficulty with linestrings and polygons. Can anyone provide guida ...

Issue with modal-embedded React text input not functioning properly

I have designed a custom modal that displays a child element function MyModal({ children, setShow, }: { children: JSX.Element; setShow: (data: boolean) => void; }) { return ( <div className="absolute top-0 w-full h-screen fle ...

Mocking an injectable Angular2 service

My setup involves Angular 2 Karma-Jasmine with a service called AService. it("test", () => { let x:any = function1('value', aService); expect(x).toEqual("value1"); }); AService now includes a method called getA(), and function1 relie ...

Several Checkbox Options with Switchable Values

My task is to create a set of three checkboxes with specific conditions when clicked. For instance, consider checkboxes 1, 2, and 3. If checkbox 1 is selected, then checkboxes 2 and 3 should be enabled. If checkbox 1 is changed to 'false', the ...

I am having trouble retrieving edge labels asynchronously in jsplumb. When I subscribe to the observable to retrieve the labels of the edges, I am receiving undefined. Is there a solution to this issue

I need to retrieve data from the backend and use it as labels for the edges instead of +N. Can someone assist me in resolving this issue? Thank you in advance. Trying to asynchronously fetch jsplumb graph edge labels ...

The selectedIndex attribute is failing to function properly for the mat-tab-nav-bar tabs in Angular Material

I've implemented the tab navigation code as shown below: <nav mat-tab-nav-bar [selectedIndex]="0"> <a mat-tab-link *ngFor="let link of navLinks; let i = index;" [routerLink]="link.path" routerLinkActive #rla="rou ...

Create an object with identical keys as another object

I need to create a mapping between two objects. The first object can have keys of any string type and values of a generic type. I want to map the second object with the same keys, allowing different types for the values (ideally extracted from the generi ...

What is the best way to sort through data if I enter more than three characters to filter the results?

Hey there, I'm currently in the process of developing a search bar that functions by displaying only filtered last names from a table when more than 3 characters are typed. The condition for filtering is empty. Here is the HTML code: <mat-form-fi ...