Firing a function in Angular2 whenever an observable property undergoes a change

Utilizing a workingData service that stores crucial data across my application, it provides an observable to the Mock workingData object.

@Injectable()
export class WorkingDataService {
  getWorkingData(): Observable<WorkingData> {
    return Observable.of(WORKINGDATA);
  }
  getSelectedDate(): Observable<Date> {
    return Observable.of(WORKINGDATA.selectedDate);
  }
}

Within the workingData object, there exists a date field known as selectedDate.

export const WORKINGDATA: WorkingData = {
  today: new Date(),
  selectedDate: new Date('11-15-2016'),
  targetDate: new Date(),
  data: []
};

This specific value can be modified by interacting with the "previous month" or "next month" buttons: https://i.sstatic.net/DyCtZ.png

By doing so, the following function (or its counterpart incrementDate()) within the cal-nav component is triggered:

decrementDate(): void {
  let newDate = new Date(this.workingData.selectedDate.getDate());
  newDate.setMonth(newDate.getMonth() - 1);
  this.workingData.monthPrior = newDate;
}

The observable automatically updates the display in all components where the workingDate service is injected. However, I now aim to activate a function within the month component (which is a sibling of the cal-nav component) every time the workingData.selectedDate changes, regardless of the originating component. How can I accomplish this?

UPDATE: It is now necessary to explicitly subscribe to the selectedDate property.

ngOnInit(): void {
  this.getWorkingData();
  this.getSelectedDate(); // Just added
}

getSelectedDate(): void{
  this._workingDataService.getSelectedDate().subscribe(selectedDate => {this.myFunc();});
}
myFunc(){
  console.log('working');
}

While this successfully invokes myFunc() during initialization, it fails to do so when the value is updated.

Answer №1

To easily receive updates from your Observable, simply subscribe in your code

this.myObservable.subscribe( data => {
  myFunction();
 });

If this method does not meet your requirements, please share additional code or specify exactly what you need

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

Exploring Angular 11 Testing: Troubleshooting Async Issues in Jest with RxJS Timer

I encountered an issue while working on a test where I received the following error message: "Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 5 ...

What is the solution for resolving the Next.js 14 next/link routing 404 error page problem?

After performing a fresh installation of Next.js on Windows using an elevated shell with the command npx create-next-app@latest, I encountered an issue. In my /src/app/components/Header.tsx file, the code looks like this: import React from 'react&apos ...

Using Javascript/HTML to enable file uploads in Rails

I'm currently facing an issue with uploading and parsing a file in Rails, as well as displaying the file content in a sortable table. I followed a tutorial on to get started. This is what my index.html.erb View file looks like: <%= form_tag impo ...

Unveiling the Mystery: Extracting the URL Parameter in AngularJS

Here is a link localhost/project/#/showprofile/18 I need to retrieve the parameter 18 in my view In the application file named app.js, I have the following configuration: .when('/showprofile/:UserID', { title: 'Show User Profile&apo ...

Retrieve the chosen date from a DatePicker using a Javascript function

Is there a way to retrieve the user-selected date using a JS function? I attempted this method: var test = $("#datepicker").datepicker( 'getDate' ); However, when I display it with an alert, it shows [object object] instead of the date. This ...

Dynamic script tags pose a potential security risk

This flickr blog post delves into the rationale behind the recent enhancements made to the people selector autocomplete feature. A significant challenge they had to address was the handling of a vast amount of data (i.e., all user contacts) on the client- ...

Course completed following the module

As a newcomer to Angular, I am facing an issue with saving data in a class and reading it into a component. It seems that the component is rushing to display results before the class has finished processing them, resulting in an error message being printed ...

Encountered an issue while importing React with webpack: Unable to resolve module 'react'

I keep encountering an issue Error: Cannot resolve module 'react' (and react-dom) while using webpack. This project setup seems to be the most challenging one I've faced, and I'm struggling to figure out why it's not functioning pr ...

Javascript in Chrome can be used to initiate and conclude profiling

Is there a way to activate the CPU Profiler in the Chrome developer window using a Javascript call? For example: chrome.cpuprofiler.start(); //perform intensive operation chrome.cpuprofiler.stop(); Currently, my only option is to manually click on "s ...

Comparing ngrx and redux for managing state in stateless components

Exploring ngrx/angular 8 for the first time, I'm curious to know if the angular approach of using an observable to bind a state value to the this context still allows a component to remain presentational and stateless. In the realm of angular/ngrx, c ...

The issue of null/undefined checks is complicated when dealing with Classes that have extendable props interfaces in Typescript

When working with classes that accept generic props, null or undefined checks may not function as expected. interface IFooProps { minDate?: Date; } 1 - In this scenario, an error "undefined is not assignable to type "Date" is encountered in the upd ...

Draggable vue includes a Textarea HTML element that allows users to easily

The issue lies in implementing the draggable functionality on a textarea element. While the textarea allows text input and deletion, trying to select the text using pointer events triggers the dragging function instead, as shown in the image below: https ...

Tips for successfully sending an interface to a generic function

Is there a way to pass an interface as a type to a generic function? I anticipate that the generic function will be expanded in the future. Perhaps the current code is not suitable for my problem? This piece of code is being duplicated across multiple fil ...

What could be causing my function to execute thrice?

I cannot seem to figure out why my tag cloud is causing the required function to run multiple times instead of just once when I click on a tag. This issue persists whether using jQuery or plain JavaScript. What am I missing? The code I have is very simple, ...

Uncovering design elements from Material UI components

The AppBar component applies certain styles to children of specific types, but only works on direct children. <AppBar title="first" iconElementRight={ <FlatButton label="first" /> }/> <AppBar title="second" iconElementRight={ <di ...

What is the best way to include a class with Knockout JS?

After going through the basic Knockout tutorial and examining various examples, I decided to try it out myself on jsFiddle. However, I encountered some issues as my attempts did not quite work. The goal is simple - I just want to add the class open to a d ...

The jQuery event for clicking is not functioning as expected when trying to display particular data from a JSON array

Three dummy users were created with a JSON array structured like this: var userArray = {"users":[ {"Name":"User1","Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2f293f286b1a2935373f2e3233343d74393537">[email& ...

How to efficiently import Xlsx and csv files using AngularJS

I am looking for a way to extract data in json format from each line of xlsx and csv files using AngularJS. Currently, I am utilizing the angular-file-upload library to access the file as shown below: $scope.LatLongUploader = new FileUploader({ //url ...

Trigger file download with ajax and php

I have been using an image picker plugin to select an image and then force it to download. Initially, I hard coded the PHP which worked perfectly fine. The download pop-up appeared and I was able to view the file without any issues. However, when trying to ...

Encounter an issue while running the angular build in production mode

Encountering an error stating "Type src/app/createreportcomponent component.ts is part of the declarations of 2 modules" while the normal development build is running smoothly. How can this error be resolved? ****App Module ts file**** import { BrowserMo ...