Communication between sibling components in Angular 2, with one component failing to subscribe to a service

I'm trying to establish communication between sibling components on the same page using a service, but it seems the listening component is not triggering when the subscribed object changes:

Service

import {Injectable}     from 'angular2/core';
import {Observable}     from 'rxjs/Observable';
import {ReportTable} from '../classes/report.table.class';
import {Subject}    from 'rxjs/Subject';

@Injectable()
export class ReportService {

    private payload = new Subject<string>();

    // Observable string streams
    payload$ = this.payload.asObservable();

    constructor() { }

    public communicate(payload: string) {
        console.log('called2');
        this.payload.next(payload);
    }
}

Broadcasting Component

import {Component, Input} from 'angular2/core';
import {CORE_DIRECTIVES} from 'angular2/common';
import {FilterComponent} from '../reports/filter.component';
import {ReportService} from '../../services/report.service';

@Component({
    selector: 'filteroptions',
    templateUrl: '/Reports/filteroptions.template.html',
    providers: [ReportService]
})

export class FilterOptionsComponent {
    displayId: string;

    constructor(private reportService: ReportService) {             
    }


    passDisplayId(displayId: string) {
        console.log('called1');
        this.reportService.communicate(displayId);
    }
}

Listening Component

import {Component, OnInit, OnDestroy} from 'angular2/core';
import {ReportService} from '../../services/riskreport.service';
import {ReportTable} from  '../../classes/riskreport.table.class';
import {HTTP_PROVIDERS}    from 'angular2/http';
import {DataTable} from 'primeng/primeng';
import {Column} from 'primeng/primeng';
import {Subscription}   from 'rxjs/Subscription';

@Component({
    selector: 'report-table',
    templateUrl: '/Reports/riskreport.table.template.html',
    providers: [ReportService, HTTP_PROVIDERS],
    directives: [DataTable, Column]
})

export class ReportTableComponent implements OnInit, OnDestroy {

    public subscription: Subscription;

    constructor(private reportService: ReportService) {
        this.subscription = this.reportService.payload$.subscribe(m => console.log('called3'));
    }

    ngOnInit() {}            

    // Prevent memory leak
    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

In my console, I can see that called1 and called2 are logged, but called3 is not. What could be causing the second component not to listen/subscribe?

Answer №1

When implementing your service, make sure to pay attention to how you declare its instances:

First instance declaration:

providers: [ReportService]

Second instance declaration:

providers: [ReportService, HTTP_PROVIDERS],

Every time a service is added to a providers array, a new instance is created. To ensure that both instances access the same service, include them in the providers array of a shared parent element.

If multiple elements use HTTP_PROVIDERS, consider moving it to a common parent element for cohesive service access.

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

Transforming an Image URL into base64 format using Angular

I'm currently facing difficulty when attempting to convert a specified image URL into base64. In my scenario, I have a string that represents the image's path. var imgUrl = `./assets/logoEmpresas/${empresa.logoUrl}` Is there a way to directly co ...

Encountering issues with integrating an external plugin with AngularJS code

For my app, I am attempting to incorporate intercom for monitoring user activity. It functions correctly when placed inside a script tag in index.html. However, I encounter an error when trying to use it in a .ts file as shown below: app/components/rocket/ ...

Importing a JSON or JSONC file into a vite/typescript project can be easily done

I am looking for a way to seamlessly share my routes between my actix-web backend and Vue with Vue-Router frontend without needing separate route files. I want to define the routes on the frontend without having to make any changes on the server side. If t ...

Ensure that the type of the value passed to the callback function is enforced within the callback function in the

One of my jQuery plugins has a prompt function that accepts a callback function with setPrompt as the only parameter: Here is an example of how the code looks: obj.prompt(function(setPrompt) { setPrompt(10); }); I am wondering if it is possible to en ...

Is there a way to make divs expand on top of existing content when hovering over them, in order to avoid needing to scroll through overflow content? I am currently working with

I am working with 9 boxes contained within divs, each box includes data that exceeds the size of the box itself (represented by Some Text repeated for demonstration purposes). I am seeking a solution where hovering over any box will cause it to enlarge and ...

Detecting clicks outside of a component and updating its state using Typescript in SolidJS

Hi there, I am currently learning the SolidJS framework and encountering an issue. I am trying to change the state of an element using directives, but for some reason it is not working. Can anyone point out what I might be doing wrong? You can find the ful ...

The setter of the computed property is failing to execute

Currently, I am working with a computed property that represents an object of a specific type defined within my Vuex Store. The goal is to utilize this property in my component using v-model. I have thoroughly set up getters and setters for this property a ...

Setting an Observable reference to null within a map operator does not have any impact

I am currently working on developing a generic DataService that includes hateoas implementation. Within this setup, there is a REST API endpoint called /root which provides all the required hateoas links. For instance, { _links : { login : { ...

Disregarding extraneous object attributes that come with a Back-End object

Seeking advice on how to handle unnecessary object properties that come with a Back-End model. Could you please share your thoughts? Imagine an API returning the following object: export class TodoObject{ public name: string; public id: number, publi ...

angular datatable pagination issue with mdb

I've been following a tutorial at this website: Unfortunately, I keep encountering an error whenever I attempt to use pagination. Cannot read property 'setMaxVisibleItemsNumberTo' of undefined This is how my HTML code looks: <table ...

What is the best way to have text wrap around an icon in my React application?

I am facing an issue while trying to display the note description over the trash icon in a React app. I have tried various methods but can't seem to achieve the desired effect. Can anyone guide me on how to get this layout? Here is what I intend to a ...

Is there a collation method for MatSort that accommodates languages with alphabetical orders differing from Unicode orders?

When it comes to the Norwegian and Danish Alphabets, the proper order of the characters is as follows: Æ Ø Å However, MatSort follows the Unicode order for these characters: Å (197) Æ (198) Ø (216) Is there a way to implement collation to addre ...

A guide on transferring received data from dataService within the parent component to the child component in Angular2

Within the context of my application, there exists a parent component named app-parent and a child component called app-child. In app-parent, I retrieve data from a DataService. @Component({ selector: 'app-parent', providers: [DataService] ...

Develop a personalized FormControl using Validators

I have designed a custom component called AComponent that utilizes Material design elements. I want to integrate this component as a formControl in my Reactive Form within the AppComponent. To achieve this, I have implemented the ControlValueAccessor inter ...

Extracting data from an array using Angular

Currently, I am developing an Angular application that involves handling an array structured like the one below. [ { Code: "123", Details:[ { Id: "1", Name: "Gary" }, { ...

Extract a section of the table

I'm looking to copy an HTML table to the clipboard, but I only want to include the rows and not the header row. Here is the structure of the table: <table style="width:100%" #table> <tr> <th class="border"></th> ...

Can Angular2+ provide a way to retrieve a list of all components that adhere to a particular interface?

Can Angular2+ provide a way to retrieve or inject a list of all components that adhere to a specific interface? I am looking to reset the state of all UI components when a certain event occurs. My thought is to define an interface called OnRest and then ...

I am facing difficulty in retrieving data from Firestore using Angular

I've been utilizing the AngularFireList provided by @angular/fire/database to retrieve data from firestore. However, despite having data in the firestore, I am unable to fetch any information from it. import { Injectable } from '@angular/core&apo ...

Can you explain the concept of `export as namespace` in a TypeScript definition file?

While browsing through some declaration files on DefinitelyTyped, I have noticed the following pattern: declare function domready(callback: () => any) : void; export = domready; export as namespace domready; I am familiar with the first two lines - d ...

What causes the error "unable to read property of undefined (reading 'length')" to be triggered while using Redis for a GraphQL Subscription?

Summary Currently working on a NestJS project with GraphQL using a laptop running Windows OS Exploring GraphQL Subscriptions with the help of <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfb8adbeafb7aeb3f2adbabbb6acf2acaabda ...