Distribute information to every recipient components using observables in Angular2

I am facing an issue where I want to send data to all elements named 'modal', but only one of them is receiving the message.

Here is my service:

@Injectable()
export class ModalService {

private _isOpen = new Subject();
isOpen$ = this._isOpen.asObservable();

open(id: string) {
    this._isOpen.next({isOpen: true, id: id});
}

close(id: string) {
    this._isOpen.next({isOpen: false, id: id});
}

and component:

import {Component, Input} from 'angular2/core';
import {Observable} from 'rxjs/Observable;
import {Subject} from 'rxjs/Subject';

import {ModalService} from './modal.service';


@Component({
     selector: 'modal',
     template: `
     <ng-content></ng-content>`,
     styleUrls: ['app/workshop/modal.component.css'],
     providers: [ModalService],

})

export class ModalComponent {

@Input() ID;

private show = false;

constructor(private _modal: ModalService){

    this._modal.isOpen$.subscribe(
        (value) => {
            console.log(value)
            if(this.ID === value.id) {
                this.show = value.isOpen;
            }
        }
    );

}

open() {
    this._modal.open(this.ID);
}

close() {
    this._modal.close(this.ID);
}

}

Everything works fine until I try to inject the service into another component and send a message to the remaining subscribers. I'm struggling to figure out how to share a message with all elements of type 'modal'. While I can hook DOM elements, I'm having difficulty with Components. Any suggestions on how I can hook all 'modal' elements to observable?

Thank you for your assistance

Answer №1

Sharing the same instance among multiple components is essential. To achieve this, simply include the service in the providers array within the main component:

@Component({
  (...)
  providers: [ ModalService ]
})
export class AppComponent {
  (...)
}

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

What is causing the loss of data when attempting to access an array field within an object?

So I've been grappling with this issue. I have a collection of objects, each containing string arrays and a string based on the following interface: export interface Subscription { uid: string; books: Array<string>; } The problem arises whe ...

Instructions for creating a dropdown menu button that can also act as a link button

I'm struggling with my HTML code and can't seem to get the button to work as a link. Even after inserting an anchor tag with a link inside, clicking on the button does nothing. <!DOCTYPE html> <html lang="en"> <head> ...

Is there a way to limit the number of rows in an array using Google App Script?

Running into an issue with my Google App Script that sends POST data from each row to an API Gateway URL. The problem seems to occur after the first 6 rows, possibly due to a stacking issue with Lambda. Any ideas on how to limit the script to processing o ...

Utilizing the Bootstrap Carousel Feature within Mezzanine

Seeking to implement a bootstrap carousel of mezzanine galleries, I aim to display all images in a single row carousel. Below is a code snippet that I've been struggling with and would like to modify it to handle an infinite number of images. {% ...

The initial $http POST in Angular ends up hitting the error path within the .then function despite the successful execution of the

Something strange is happening to me. This peculiar behavior occurs only on the initial POST request. However, when I resubmit the form, the subsequent requests work perfectly fine. The first $http post call leads to the error function in .then, even thou ...

What is the best way to combine JSON objects from a two-dimensional array into a single array using JavaScript?

I have a JSON object within an array that I want to push to an employeeArray. employeeArray =[ [ { "ID":"967", "NAME":"Dang, Lance D", "Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e426f6 ...

What is the best way to determine if an identification number exists within the array containing team members' IDs?

In my Node.js project, I have a workspace schema model (shown below). After a user logs into my application, I want to display information about a workspace only if they created it or are a team member of that workspace. To find workspaces created by the ...

Error: Unable to access the 'push' property of an undefined variable in Ionic 3

I encountered an issue while attempting to redirect to a different page after a successful callback. The error message that I received was TypeError: Cannot read property 'push' of undefined this.http.post('http://localhost:3030/users&apos ...

React component using Highcharts is displaying categories as numeric values instead of text

Incorporating the highcharts-react package (https://github.com/highcharts/highcharts-react) into my Laravel project has presented a unique challenge. I am attempting to fetch data from my reducer and transform it into a string to populate the categories in ...

What is causing the ESLint error when trying to use an async function that returns a Promise?

In my Next.js application, I have defined an async function with Promise return and used it as an event handler for an HTML anchor element. However, when I try to run my code, ESLint throws the following error: "Promise-returning function provided t ...

Does the ngIf directive cause a re-evaluation of variables when used with one-time-binding in AngularJS?

I recently had a colleague at work demonstrate a peculiar quirk with one-time binding in Angular. Scenario: Imagine having an element with text being bound using one-time binding inside a block that is conditional on ng-if. If you update the value, say b ...

Simplest method for storing small amounts of data

As a beginner in coding, I may be asking a question that seems obvious to some. I successfully created a web app using html/JavaScript that collects user input and transforms it into a variable of my interest. The data I want to extract is stored in an arr ...

"Deleting an element from an array with a click of a button

Whenever I click on an element in the array, it gets added to the new array at the end <div class="grid"> <div class="cell" v-for="item in posts" :key="item"> <img :class="{active: item.isActive}" :src="item.url" alt width="293px" hei ...

Is it possible to generate unique identifiers for v-for keys using vue-uuid?

I'm attempting to utilize a random string (UUID v4) using vue-uuid for existing items and future additions to the list in my to-do list style application. However, I'm uncertain about the correct syntax to use. After installation, I included it ...

Issue with Window.close() not working to close the current tab

When navigating from my webpage to a new page in a different tab, I would like for my original webpage to close once the new tab has loaded. For example, if I am on pageA and I open pageB using window.open(), I want pageA to close when pageB is opened. I a ...

Utilizing Vuex Store in Vue for BeforeRouteEnter Hook to Interrupt Navigation

I'm in the process of configuring vue-router to verify a set of permissions before proceeding with navigation to a new route. These permissions are stored in vuex, and I am looking for a way to avoid passing them as props each time. Even though I use ...

Errors were encountered while parsing providers in SystemJS with angular2-in-memory-web-api

Having some trouble integrating angular2-in-memory-web-api into my project. Progress has been made, but now encountering (SystemJS) Provider parse errors: (...). Not sure what I'm missing, everything compiles fine and no 404 errors are showing up, so ...

Using Immutable JS to Generate an OrderedMap from a List

I possess a List const results = [94, 88, 121, 17]; and I also own a Map const posts = { 94: { title: 'Foo bar', content: 'Blah blah blah...' }, 88: { title: 'Bar Foo', content: 'Blah blah blah...' }, 121 ...

Utilize nodemailer in Angular 6 to effortlessly send emails

I am currently experiencing an issue with my email service form in my Angular 6 application integrated with Node.js. I have set up the form using Bootstrap and Nodemailer for sending emails, but it seems to not be working as expected. Whenever I attempt to ...

Comparing Embedded and Linked JS/CSS

In my experience, I understand the advantages of using linked CSS over embedded and inline styles for better maintainability and modularity. However, I have come across information suggesting that in certain mobile web development applications, it may be m ...