The UI elements are failing to reflect the changes in the data

In an attempt to establish communication between three components on a webpage using a data service, I have a Create/Edit component for adding events, a "next events" component for accepting/declining events, and a Calendar component for displaying upcoming events.

The service maintains an array of events that should be visible to the other components. Any updates made to an event should be distributed to all components. I decided to utilize Rxjs's BehaviorSubject but encountered a roadblock. After creating a new event and handling all logic in the service component, the newly added event is not displayed unless I refresh the Calendar component.

Service component class

 EXPORT CLASS eventService { 
  public Sevents = new BehaviorSubject<AgendaEvent[]>([]);
  private eventsToManipulate;

  constructor() { 
      this.getAllData();
  }

  getAllData() {
    this.http.get(url).subscribe(data => { 
            // Mapping events from API to eventsToManipulate array
        this.Sevents.next(eventsToManipulate);
    }) 
  }

  addNewData(event) { 
    this.http.post(url, event).subscribe( 
    {
        this.eventsToManipulate.push(event);  
        this.Sevents.next(this.eventsToManipulate);
    });
  }

}

View Component class

EXPORT CLASS eventView { 
events = new Array<Events>();

ngOnInit() {
     this.eventService .Sevents.subscribe( element => {
     console.log('this is element', element);
     this.events = element;
    })

}

Based on my understanding of RXjs, the BehaviorSubject should notify all subscribers about new data immediately. However, my code does not seem to achieve this desired functionality.

Previously, I relied on event Emitters to repeatedly load data into components to achieve the desired effect. Now, I am seeking a more efficient implementation with RxJs.

Answer №1

To monitor changes, you must convert a BehaviorSubject into an Observable and then subscribe to it.

Give this code a try:

EXPORT CLASS eventService { 
  private Sevents = new BehaviorSubject<AgendaEvent[]>([]);
  public Sevents$: Observable<AgendaEvent[]>;
  private eventsToManipulate;

  constructor() { 
    this.Sevents$ = this.Sevents.asObservable();
    this.getAllData();
  }
  ...
}

Here is the view component class:

EXPORT CLASS eventView { 
  events = new Array<Events>();

  ngOnInit() {
    this.eventService.Sevents$.subscribe( element => {
      console.log('this is element', element);
      this.events = element;
    })

}

I was able to achieve something similar by following this link.

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

Modifying the date format of the ag-Grid date filter

On my Angular 5.2.11 application, I utilize ag-grid to showcase a table. The date column is configured with the default date filter agDateColumnFilter as per the documentation. After enabling browserDatePicker: true, the Datepicker displays dates in the ...

Conceal the PayPal Button

Currently, I'm facing a challenge where I need to dynamically show or hide a PayPal button based on the status of my switch. The issue is that once the PayPal button is displayed, it remains visible even if the switch is toggled back to credit card pa ...

Angular2 - Retrieve data in XLS format from RestService并下载

I am looking to create a web service using Apache POI to generate an Excel file (xls, xlsx). Below is the snippet of code I have put together: @RequestMapping(value = "/export", method = RequestMethod.GET) public void exportXlsx(HttpServletResponse respon ...

"What are the necessary components to include in UserDTO and what is the reasoning behind their

Presenting the User entity: package com.yogesh.juvenilebackend.Model; import jakarta.annotation.Generated; import jakarta.persistence.*; import lombok.*; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor @RequiredArgsConstructor public class ...

Prevent repetition of errors during compiling in the ahead-of-time (AOT

I need assistance with optimizing my codebase in Angular 2 using angular-cli. When I run the command "ng build --prod", I encounter an error that is preventing the output of the dist folder. This error claims that there is a duplicate identifier in one of ...

When faced with the error message "Typescript property does not exist on union type" it becomes difficult to assess the variable

This question is a continuation of the previous discussion on Typescript property does not exist on union type. One solution suggested was to utilize the in operator to evaluate objects within the union. Here's an example: type Obj1 = { message: stri ...

Dependencies for Angular 5 plugins

Will the total list of dependencies for the application be a combination of all unique dependencies from Angular plugins with their own managed dependencies in Node, even if they have some overlapping dependencies? For example, if plugin 1 has 1000 depen ...

What improvements can I implement in this React Component to enhance its efficiency?

Seeking advice on improving the efficiency of this React Component. I suspect there is code repetition in the onIncrement function that could be refactored for better optimization. Note that the maxValue prop is optional. ButtonStepper.tsx: // Definition ...

Utilizing ngmodel to dynamically populate select dropdowns in Angular version 8

In the form, there are two dropdown menus for selecting start time and end time. The first dropdown menu uses a time array to select a time, and then the index of this selected time is used to create an array for the second dropdown menu. This ensures that ...

Is there a marble experiment that will alter its results when a function is executed?

Within Angular 8, there exists a service that contains a readonly Observable property. This property is created from a BehaviorSubject<string> which holds a string describing the current state of the service. Additionally, the service includes method ...

Utilizing data from the home component in another component: A guide

Here is the code I am working with, showcasing how to utilize (this.categoryType) in another component: getCategoryDetails(){ return this.http.get('ip/ramu/api/api/…') .map((res:Response) => res.json()); } The above code snippet is utilize ...

Tips for implementing a filtering function within an array of objects

I am struggling to implement a filter search feature in my ionic mobile application for an array of objects. The array is structured like this: initializeItems() { this.items = [ {Place:"Dumaguete city", date:"February 2 2018"}, {Place:"Sibulan", date: ...

Tips for creating a carousel with Angular 9 to showcase numerous items

I've got this code snippet that I'm working on. I want to incorporate a Carousel feature using Angular 9 without relying on any external libraries. Currently, all the data items are appearing in a single row (they are exceeding the specified bor ...

When converting an NgbDate to a moment for formatting needs, there is a problem with the first month being assigned as 0 instead of 1

I am encountering a challenge with my Ngb-Datepicker that allows for a range selection. To customize the output format, I am using moment.js to convert the NgbDate into a moment object (e.g., Wed Jan 23). One issue I encountered was that NgbDates assign J ...

Using .htaccess with Angular is specifically designed to function within a subfolder of

After deploying my app on a Debian 11 Apache server within the folder var/www/html (specifically in var/www/html/foo), I encountered issues with routing and hard refreshing, resulting in a 404 error whenever I attempted to refresh a page. The Angular app c ...

The database did not respond, causing the API to resolve without sending a response for the specified endpoint (/api/dates). This could potentially lead to requests becoming stalled in Next

I have been attempting to retrieve a list of dates from my database in a straightforward manner, but unfortunately, I am not receiving any response (even after trying to log the response data to the console). The only feedback I seem to be getting when sel ...

Showcasing diverse content with an Angular Dropdown Menu

I'm currently developing an angular application, and I've encountered a difficulty in displaying the user's selection from a dropdown menu. To elaborate, when a user selects a state like Texas, I want to show information such as the period, ...

Function arity-based type guard

Consider a scenario where there is a function with multiple optional parameters. Why does the function's arity not have a type guard based on the arguments keyword and what are some solutions that do not require altering the implementation or resorti ...

Why is it that PowerShell cannot execute Angular commands?

Recently, I started diving into Angular and encountered an issue using PowerShell in Windows. Every time I run an angular command like: ng new new-app or ng serve I keep getting this error message: ng : File C:\Users\< username >\ ...

Adding and removing/hiding tab-panels in Angular 4 with PrimeNg: A step-by-step guide

I'm currently working on a tabView project with a list of tab-panels. However, I am struggling to find a way to dynamically hide and unhide one of the tab panels based on specific runtime conditions. Does anyone have any suggestions or insights on how ...