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

Displaying multiple lines in an alert box using Angular 8

I need assistance in displaying an alert message when the user selects a checkbox. We have a shared alert service component that is being utilized by every module. My current code snippet is as follows: if(this.checkboxvalue) { this.al ...

Encountering a ReferenceError in Angular 4 due to d3 not being defined when importing in a module

I'm looking to incorporate these imports into my angular 4 app.module, rather than adding them directly to my index file. In app.module.ts -> import d3 from "d3"; console.log(d3) // Confirming successful import of D3 import nvd3 from "nvd3"; H ...

Dynamically loading classes in TypeScript without using default export

Is there a way to dynamically load classes in TypeScript without using a default export method? I have managed to make it work partly, but I am looking for a solution that doesn't require a default export: export default class Test extends Base { ... ...

Error in Angular 2 after transition to @types: encountering "require" name not found issue

After transitioning my project from old typings to types-publisher, I have successfully resolved most of my dependencies. However, I am consistently encountering an error that reads Cannot find name 'require'. Below is a snippet from my tsconfig. ...

Creating the document.ready function in Angular2 with JQuery

I am seeking assistance to modify the JQuery function so that it can run without the requirement of a button click. Currently, the function only executes when a button is clicked. Code declare var jQuery: any; @Component({ selector: 'home-component ...

Pinia store encountering a Typescript Vue component issue: error message "The property 'testStore' does not exist on the 'CreateComponentPublicInstance' type."

Within my <script setup> block, I have imported my testStore. However, whenever I attempt to use this.testStore.name in my Vue file, Vetur displays the following error: Property 'testStore' does not exist on type 'CreateComponentPublic ...

Implementing Routes in Express Using Typescript Classes

Seeking assistance in converting a Node.js project that utilizes Express.js. The objective is to achieve something similar to the setup in the App.ts file. In pure Javascript, the solution remains unchanged, except that instead of a class, it involves a mo ...

I have a data.json file with a URL that I need to access in my view using Angular. How can I achieve this without relying on innerHTML?

Here is the JSON file data.json that I am referring to: { "id": 1, "title": "POC", "desc": "<a href='www.google.com'>HOMEPAGE</a>", "status": "done", "percentage_finished": 100 } I am tryi ...

Modify certain parameters in the current route using Angular 6 router

Within my Angular 6 setup, the URLs are structured as follows: /{language}/{app_section}/{object_id}/{view}?queryparams... All sections of the application utilize a language selector component, which is included in the template of a parent route to ensur ...

The 'type' property within the NGRX Effect is not present in the type Observable<any[]>

I am currently in the process of upgrading my Angular app from version 6 to version 7. Additionally, I am upgrading the TypeScript version from 2.7.2 to 3.1.6. The issue I'm encountering is that TypeScript is flagging an error stating that my ngrx ef ...

QueryFailedError: Null values found in the "price" column - TypeORM - PostgreSQL

I have developed a straightforward table: import { Column, Entity, PrimaryGeneratedColumn } from "typeorm" @Entity() export class Test { @PrimaryGeneratedColumn() public id!: number @Column({ nullable: false }) public name!: string @ ...

Protractor performs the afterEach function prior to the expectations being met

I am completely baffled by the behavior of this code. Everything seems to be executing correctly up until the 'expect' statement, at which point it abruptly navigates to a new page and runs the afterEach function. I've tried various solution ...

Utilizing Angular 2 and Node JS for both backend and frontend development

I'm a bit puzzled on how to go about implementing this, particularly with routing. How should I handle routing for both the backend and frontend, considering that the source (CSS, HTML, JS) might differ between the two? Thank you. ...

What is the best way to integrate Next.js with Strapi (or the other way around)?

My goal is to develop an application utilizing Next.js for the frontend, fetching data from a Strapi API hosted on the same server. The plan is to have Strapi handle API and admin routes, while Next.js manages all other routes. I intend to use fetch in Nex ...

With *ngFor in Angular, radio buttons are designed so that only one can be selected

My goal is to create a questionnaire form with various questions and multiple choice options using radio buttons. All the questions and options are stored in a json file. To display these questions and options, I am utilizing nested ngFor loops to differ ...

The plugin needed for the 'autoprefixer' task could not be located

Starting out in the world of Angular 2 development can be overwhelming, especially when trying to integrate with the Play framework on the back-end side. I recently came across a helpful post by Denis Sinyakov that walks through setting up this integratio ...

Displaying Well-Formatted XML in Angular2 Using Typescript

After receiving this XML string from the server: <find-item-command xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" find-method="Criteria" item-class="com" only-id="false" xsi:schemaLocation=""> <criteria> <criterion> <descripto ...

Navigating to a specific section upon clicking

Imagine a scenario where there is a landing page with a button. When the button is clicked, redirection to another page with multiple components occurs. Each component on this new page serves a different function. Additionally, the desired functionality in ...

Is there a way to use Jest spyOn to monitor a function that is returned by another function?

I'm curious about why the final assertion (expect(msgSpy).toBeCalled()) in this code snippet is failing. What adjustments should be made to ensure it passes? it('spyOn test', () => { const newClient = () => { const getMsg = ...

What is the most effective way to retrieve cursors from individual entities in a Google Cloud Datastore query?

I am currently working on integrating Google Cloud Datastore into my NodeJS application. One issue I have encountered is that when making a query, only the end cursor is returned by default, rather than the cursor for each entity in the response. For insta ...