Communication between related components in Angular involving siblings

I am currently working in Angular 4 with sibling components, where there are no parent-child relationships, only siblings.

One of the siblings is able to successfully retrieve data, particularly the ID from the URL using the code snippet below:

public getId () {
    const id = +this.route.snapshot.paramMap.get('id');
    // console.log (id); //working! 
    return id
}

However, the other sibling attempted to do the same but could not retrieve the ID, even though they are on the same route. The reason for this remains a mystery to me.

My solution was to pass the ID from one sibling component to the other. After researching, I found examples for passing data between parent and child components but not between siblings. It seems that using a service to pass the data is the best approach, following this tutorial.

Despite my efforts, something doesn't seem to be working correctly. So, where exactly is the issue?

Component one: This component is responsible for fetching the ID from the URL.

urlId: number;
public getId () {
    const id = +this.route.snapshot.paramMap.get('id');
    // console.log (id); //working! 
    return id
}
ngOnInit(): void {
    const id = +this.getId ();                   
    this.taskService.newId(id)
}

The service: This service updates the 'noId' variable using the function newID().

private noId = new BehaviorSubject<number>(0);
defaultId = this.noId.asObservable();

newId(urlId: number) {
    this.noId.next(urlId);
    console.log (urlId); // this still working
}

Component two: This component should receive the data after running the ngOnInit() function, but nothing is happening.

urlId: number;
ngOnInit() {
    this.taskService.defaultId.subscribe(urlId => this.urlId = urlId)
    console.log (this.urlId); //return 0, or the same value as private noId 
}

Unfortunately, Component 2 is not receiving updated data. What could be causing this issue?

Answer №1

To start, simply create a subject within your service.

const idSubject = new Subject<number>();

In the sibling component where you need to access the id, insert this line of code.

this.taskService.idSub$.next(id);

In the sibling component where you want to use the id, add the following code:

this.taskService.subscribe(id => {
  console.log(id);
});

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

Converting HTML and CSS into a PDF using JavaScript

I am on the lookout for libraries that can cater to my specific needs, as I haven't found one that fits perfectly yet. My setup involves Node.js on Express.js for the backend, and html/css/js for the front-end. Browser support includes IE8 and up, chr ...

Automated Testing with Robot Framework: Utilizing Javascript to Click on a Button

Inspecting the web page <span jsslot=""> <button class="LkLjZd ScJHi IfEcue HPiPcc KXT7c" jsaction="click:yTqzwd" jsname="HxVe9c" autofocus="">Click Here</button> </span> I am tryin ...

Retrieving information from a JSON file using React

Hello everyone, I'm currently working on creating a dynamic menu that pulls its items from JSON data. I am using React and struggling with the correct syntax. Here is the sample data: { "name": "menu", "childr ...

Guaranteeing the sequential execution of JavaScript functions

For weeks, I've been struggling with a program that utilizes ajax post methods and dataTables. It has become clear to me that my understanding of how javascript operates is lacking. Below is the javascript code: $('#SaveTimeSheet').click(fu ...

How to achieve the functionality of ocibindbyname in JavaScript

I am currently utilizing an HTA page that is coded in JavaScript to monitor various Oracle tables. My goal is to optimize the Oracle query caching by using bind variables, similar to how I implemented it in a PHP environment with this code: $sql = "selec ...

Guide on implementing text/ng-template script section in jsfiddle

My current challenge involves creating a jsfiddle that utilizes AngularJS to display two calendar controls. While my code functions properly when run locally, I've encountered an issue with including the template code via a script tag on jsfiddle: ht ...

Display a JavaScript dialogue box containing a PHP variable

Is there a way to display the correct JavaScript box when using a While loop in PHP? Here is the code snippet: while($result= mysql_fetch_array($data)){ <tr class="<?php echo $style;?>"> <td><?php echo $result['commis ...

Using Boolean as a prop in Vue.js

Creating a Vue form to ask a question involves making a component: <template> <div class="flex flex-col items-center justify-center gap-2"> <div class="flex w-[80%] items-center justify-center gap-2 rounded-3xl p-2" ...

Even when using module.exports, NodeJS and MongoDB are still experiencing issues with variable definitions slipping away

Hello there, I'm currently facing an issue where I am trying to retrieve partner names from my MongoDB database and assign them to variables within a list. However, when I attempt to export this information, it seems to lose its definition. Can anyone ...

How can I retrieve the value of a nested reactive form in Angular?

I'm working with a nested form setup that looks like this: profileForm = new FormGroup({ firstName: new FormControl(''), lastName: new FormControl(''), address: new FormGroup({ street: new FormControl(''), ...

Is the "Illegal invocation" error popping up when using the POST method in AJAX?

Is there a way to retrieve JSON data using the POST method in Ajax? I attempted to use the code below but encountered an error: TypeError: Illegal invocation By following the link above, I was able to access JSON-formatted data. However, please note th ...

Does an event fire after the onclick event completes?

After an onclick event, I need a particular code to be executed. This works well on mobile devices using touchstart and touchend events. However, is there an equivalent event for computers? This is how my current code looks like: document.getElementById( ...

What is the best way to incorporate a third-party element into Vue using a script tag?

I am in the process of developing a website and I would like to include a widget that links to a podcast on BuzzSprout. Initially, I created the site using HTML to test out different designs, but now I am looking to transition it to VueJS. In my HTML vers ...

Having trouble shutting down Metro Bundler on Windows?

While working on my React Native development, I regularly use npm start to get things going. However, I've run into an issue recently when trying to stop the process using Ctrl + c. It seems like I can no longer use npm start smoothly: ERROR Metro ...

Process called gulp useref eliminates certain files from the pipeline

Is there a way to exclude the gulp.src file from output? I am aiming to bundle only JavaScript and output .js files, not HTML. The following blocks in base.html are utilized for bundling JavaScript with gulp-useref: <!-- build:js app.core.js --> &l ...

What methods can a server use to identify if JQuery Ajax's "withCredentials: true" option was utilized for CORS requests?

Currently, I am working on integrating CORS (Cross-origin resource sharing) into a framework. I understand that when an XMLHttpRequest request is made using Jquery's ajax(...) with the withCredentials property set to true, the server must specificall ...

Simplified method of connecting dynamic components without needing to remember functions in jQuery

I have a page where users can freely move, resize, and modify content. The basic setup is as follows: $('.element').on().resizable().draggable(); When this code is called on page load, it allows elements to be resizable and draggable. The issu ...

Creating functional dropdown menus with popperjs in the latest Bootstrap version 5

Currently, I am attempting to implement dropdown menus in Bootstrap 5. According to my research, this feature requires Popper.js integration, but I am uncertain of the correct way to include it in my Laravel project that utilizes Laravel Mix. I have made ...

Adjusting CSS to switch up the color scheme

Is there a way to allow users to change the background color of pull quotes by using the input type="color tag within a form element? Below is my current HTML structure: <form action="change.php" method="post"> name: <input type="text"> ...

Having trouble receiving a response from axios

My goal is to use axios to submit a blog post and display a response message. If the response is "success," the process should proceed. For testing purposes, I am only using console.log("success ok"). However, I encountered a puzzling issue that I cannot f ...