How to update an Angular 2 component using a shared service

My question is regarding updating components in Angular 4.

The layout of my page is as follows:

Product Component

  • Product Filter Component
  • Product List Component

I am looking to link the Product Filter and Product List components so that when a user changes their filter preference, the product list data updates accordingly.

I have done some research and it seems creating a service might be the solution, but I am unsure about how to create one and how services function. (I am still learning about Angular 2 / 4 and this is my first experience with a JavaScript framework).

Answer №1

Develop a brand new feature for subscribing to events from the ProductFilterComponent.

import { Injectable } from '@angular/core';
import { Observable, Subject, ReplaySubject } from 'rxjs';

@Injectable()
export class EventSubscribeService {

  private eventSubject: Subject<any> = new ReplaySubject(1);

  constructor() { }

// set observable of this subject
  get $getEventSubject(): Observable<any> {
    return this.eventSubject.asObservable();
  }
// remove from observer
  resetEventObserver(): void {
    this.eventSubject = new ReplaySubject(1);
  }
// send event to observers
  sendCustomEvent():void {
    this.eventSubject.next(true);
  }

}

Then include this service as a provider in the Module that contains the ProductCompont and its child components.

@NgModule({
...
providers: [
    ...
    EventSubscribeService
    ...
  ],
...

The next steps are quite simple. (* Just a reminder to define an instance of the service in the constructor. I mention this because you're still getting familiar with Angular. Hopefully, you already know how to use services. Sorry for the repetition :)).

The FilterChangeEvent in the ProductFilterComponent could be implemented like this.

EDIT : Template of ProductFilterComponent

...
<button class="btn btn-default" (click)="onFilterChangeEvent($event)">ChangeFilterButton<button>
...

UPDATE : Handling the Button Click Event

onFilterChangeEvent(param:any):void {
    this.serviceInstance.sendCustomEvent();
  }

Lastly, subscribe to the event in the ProductListComponent.

 constructor(
      private serviceInstance: EventSubscribeService,
  ) {
    this.serviceInstance.$getEventSubject.subscribe(event => {
      // Perform desired actions here
    });
  }


ngOnDestroy() {
    this.serviceInstance.resetEventObserver();
  }

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

Tips for Maintaining User Data Across Pages in React using React-Router-Dom and Context

I've been tackling the login functionality of a client-side application. Utilizing React alongside TypeScript, I've incorporated react-router-dom and Context to manage the user's data when they log in. However, upon refreshing the page, the ...

Using TypeScript to automatically deduce the output type of a function by analyzing the recursive input type

I am currently working on developing an ORM for a graph database using TypeScript. Specifically, I am focusing on enhancing the "find" method to retrieve a list of a specific entity. The goal is to allow the function to accept a structure detailing the joi ...

Display a semantic-ui-react popup in React utilizing Typescript, without the need for a button or anchor tag to trigger it

Is there a way to trigger a popup that displays "No Data Found" if the backend API returns no data? I've been trying to implement this feature without success. Any assistance would be greatly appreciated. I'm currently making a fetch call to retr ...

Centralized MUI design for varying screen dimensions

I am struggling to perfectly center my modal box in the middle of the screen. The problem arises when the screen size changes, causing the box to be misaligned. I attempted using top:50% and left: 50%, but this did not effectively center the box. center ...

Arrange a JavaScript map based on its values and ensure that a specific field index remains at the top position

I'm sure this question may seem simple to some, but as a JavaScript novice, I couldn't find the answer myself. Here is the code snippet I'm working with: Let map = new Map<String,String> map.set('0', select) map.set('1&a ...

Determining the type of a keyof T in Typescript

I am currently working on developing a reusable function that takes an observable and applies various operators to return another observable. One issue I am facing is getting the correct type for the value based on the use of the key. The code snippet bel ...

What benefits does a bundler offer when releasing packages on npm?

After working with Node.js for many years, I recently ventured into publishing my first Node.JS package for a wider audience. Feeling lost at the beginning, I turned to Google for guidance on how to do this specifically for typescript and stumbled upon thi ...

Converting Scss to css during the compilation process in Angular

Seeking assistance with .css and .scss file conversion. I am in need of help with generating or updating a .css file from an existing .scss file during compilation. To explain further: when writing code, everything is going smoothly until I decide to save ...

Guide for building a Template-driven formArray in Angular

I am currently implementing a fixed number of checkboxes that are being bound using a for loop. <ul> <li *ngFor="let chk of checkboxes"> <input type="checkbox" [id]="chk.id" [value]="chk.value&q ...

Tips for creating a window closing event handler in Angular 2

Can someone guide me on how to create a window closing event handler in Angular 2, specifically for closing and not refreshing the page? I am unable to use window.onBeforeunLoad(); method. ...

Please ensure that the property name is a valid type, such as 'string', 'number', 'symbol', or 'any'

Can anyone help me convert this JavaScript file to Typescript? import React, { useState } from 'react'; import { Button } from './Button'; import { Link } from 'react-router-dom'; import './Navbar.css'; import Settin ...

Steps for personalizing the dataset on a PrimeNG bar graph

I'm currently working with primeng in an Angular project and I need to create a bar chart where the last two horizontal bars have different colors. Right now, the last two bars are incorrectly being assigned to represent dogs and cats. My goal is to ...

The Selenium tests are running smoothly, however, despite their successful execution, I am not receiving any pass results as the assertions seem

Currently, I am in the process of incorporating Selenium (v4.18.1) tests into an Angular web application specifically for the Microsoft Edge browser (v122.0.2365.59). The necessary Microsoft Edge WebDriver (v122.0.2365.59) has been successfully installed. ...

Create an alternate name for a specific type of key within a nested record

There are three simple types available: const structureTypes = z.enum(["atom","molecule"]) const atomTypes = z.enum(["oxygen","hydrogen"]) const moleculeTypes = z.enum(["water","ammonia"]) The goal is to define a type for a cache where the keys correspond ...

By default, all groups in the Kendo UI Angular 2 Grid are collapsed

Just started using the new Kendo UI for Angular 2 Grid and I have a question - is it possible to collapse all groups by default when grouping data? I noticed there is a method called collapseGroup(), but it's unclear how to use it or if there's ...

Is it possible to efficiently utilize Map/Set in TypeScript/JavaScript when working with objects?

I'm currently transitioning from Java to TypeScript and I've encountered an issue with working with objects in hashmaps and hashsets. In Java, I would simply override the hashCode method to easily manipulate these data structures. Is there a simi ...

Enhance TypeScript class declarations with additional properties

Our company has developed its own test framework for our software because we found it difficult to use an open-source framework within the context of our specific development needs. Recently, I took on the task of creating Typescript Definition Files to e ...

What is the way to send custom properties to TypeScript in combination with StyledComponents?

Encountering an error while attempting to implement Styled Components 3 with TypeScript: TS2365: Operator '<' cannot be applied to types 'ThemedStyledFunction<{}, any, DetailedHTMLProps<TableHTMLAttributes<HTMLTableElement>, ...

Issue encountered when attempting to access disk JSON data: 404 error code detected

I am attempting to retrieve JSON data from the disk using a service: import { Product } from './../models/Product'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient } from &apo ...

Tips for inserting a line break within the output of an Angular pipe

Is there a way to display dates on separate lines in an Angular pipe? <th>{{(date | date: 'EEE MMM d')}}</th> Currently, the output is displayed like Mon Jul 20 - all in the same line. But I want it to be displayed like: Mon Jul ...