Sharing an object { } between sibling components in Angular 5

I'm feeling a bit lost here...

So, I have two sibling components. The first component fetches some data and I want to share that data with the second component, so I created a service:

Data Sharing Service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class DataService {
    private dataSource = new BehaviorSubject<Object>({});
    data = this.dataSource.asObservable();

    updateData(data) {
        this.dataSource.next(data);
    }
}

In my first component...

this.activatedRoute.params.subscribe(params => {
  this.id = params.id;
  this._dataNotification.getSingledataNotification(this.id)
    .subscribe(result => {
      this.data = result;
      this._dataService.updateData(this.data);
    });
});

And in my second component...

getData() {
    this._dataService.data.subscribe((result) => {
        this.data = result;
        console.log(this.data);
    });
}

The issue is that even though I pass data from the first component to the service and then try to access it in the second component, I only see an empty object when I log it. What am I missing?

UPDATE

After moving the updateData function to an onChanges lifecycle event, everything seems to be working fine now.

Thanks for your help!

Answer №1

This code snippet demonstrates the creation of a service to manage message events.

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

@Injectable()
export class MessageService {
  private subject = new Subject<Message>();

  send(key: string, value: any) {
    this.subject.next({ key, value });
  }

  get(): Observable<Message> {
    return this.subject.asObservable();
  }
}

class Message {
  constructor(
    public key: string,
    public value: any) { }
}

This section listens for events and executes a particular action when the desired event occurs.

import { Subscription } from 'rxjs/Subscription';
private subscription: Subscription;

constructor(
  private messageService: MessageService,
) {}

ngOnInit() {
  this.subscription = this.messageService.get().subscribe(message => {
    if (message.key === 'desired_message_key') {
      this.dosth()
    }
  });
}

To send an object from one service to another, use the 'send' method in the MessageService and subscribe to it in the target service.

Answer №2

I encountered a similar issue when I had to tackle the same situation.

The key to solving it is not to fetch the data in the receiving component within the onInit() method. Instead, retrieve it using an onChanges() method or trigger it through an event (such as a button click). This approach will provide you with the object containing the necessary values.

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

Managing state with Apollo within a component

Greetings and thank you for taking the time to help me out. I am currently diving into the world of Apollo and React, but it seems like I am struggling with some logic here. On my main page index.js, I have initialized Apollo in the following way: export c ...

Functionality not functioning within Shadow DOM

After creating and exporting an Angular Element as a single script tag (user-poll.js), using the element on a host site is simple. Just include the following two lines: <user-poll></user-poll> <script src="path/to/user-poll.js"></sc ...

Javascript unable to update the DOM

I've been working on a project to prototype a simple functionality using JavaScript for learning purposes. However, I've encountered an issue where the contents within the <p> tag are not updating, and I'm currently stuck. Here's ...

problems encountered while trying to increment ng-click function in Angular JS and Ionic

I'm currently working on developing a quiz using Angular JS and Ionic Framework. However, I've encountered an issue: The "Continue" button is not functioning as expected when clicked (using ng-click) to move to the next question. &l ...

What is the most effective approach for annotating TypeScript abstract classes that are dynamically loaded?

I am in the process of developing a library that allows for the integration of external implementations, and I am exploring the optimal approach to defining types for these implementations. Illustration abstract class Creature { public abstract makeN ...

execute an ajax request without including any authentication headers

I am looking to create an ajax call with authorization headers only when the user enters a username and password. If these variables are empty, I need to create an ajax call without authorization headers. Is it possible to achieve this using just one aja ...

The quickForm Meteor encountered an exception in the template helper: There was an error stating that Recipes is not within the window

I'm having trouble getting the app to work on Meteor. The quickform is not connecting to my Collection. "Error: Recipes is not in the window scope" Can anyone offer assistance with this issue? Below is my quickform code: <template name="NewRe ...

Slide containing Ionic list views

In my Ionic app, I am using ion-slide-box with 3 slides. Each slide contains an ion-list (table view) with varying numbers of items. The issue is that when scrolling through the shorter list items, it shows empty content due to the taller sibling list taki ...

Implement functionality in Angular to perform tasks when the page is reloaded

I need to perform certain actions in Angular when the page is reloaded, such as adding items to local storage before the page loads and removing items after the page has fully loaded. In other words, I want to execute some tasks both before and after refr ...

What is the best way to run code once a callback function has completed its task?

I am looking for a way to execute line(s) of code after every callback function has finished processing. Currently, I am utilizing the rcon package to send a rcon command to a Half-Life Dedicated Server (HLDS) hosting Counter Strike 1.6 server and receive ...

npm update fails to update specific packages

After React was updated to version 0.15 to address the issue of excessive generation of tags, I made the decision to update my project.</p> <p>However, when I ran the command <code>npm update, it only updated to version 0.14.8. Running ...

Error in Node.js: the function "myFunction" is not defined

Utilizing the fcm-node package to facilitate sending notifications from the Express API route to the app via a registration token. The function being used is as follows: const FCM = require('fcm-node'); const serverKey = ... const fcm = new FCM( ...

Unable to successfully import data from vue using vue-chartjs

Encountering an error in my Vue 2 project after compilation: Failed to compile. ./node_modules/vue-chartjs/dist/index.js 85:11-26 "export 'defineComponent' was not found in 'vue' The specific line in the above file triggering thi ...

How can I retrieve JSON data from an AJAX request on an HTML page?

How can I display my JSON data on an HTML page using this JavaScript code? $.ajax({ url : 'auth.json', type: "GET", dataType : "jsonp", success: function(result) { $.each(result, function(i, v) { // Loop through each record in ...

Is it possible to compare JSON data in MM/DD/YYYY format within a controller to today's date using a custom filter, and then display the filtered list in an array?

I'm struggling to compare today's date obtained from new Date() with a date in MM/DD/YYYY format and then filter the array data using my own custom filter. Is there a way to achieve this? I attempted to set the hours to (0,0,0,0) and compare them ...

The Ajax validation form mistakenly redirects the echoes to a different page instead of the intended page for displaying the output

I am currently working on creating an ajax-form to validate the client-side server of my sign-up form. My goal is to have error messages displayed on the same page where they are triggered, without loading a separate page. Below is the code from my (sign ...

What is preventing me from being able to retrieve my parameters using the 'GET' method in Express' Router()?

When dealing with an overloaded fetch function in my Angular service 'PostSvc', the goal is to retrieve either all posts from the database or only the posts belonging to a specific user if that user is provided as an argument... The user object ...

How can I retrieve the input value on the current page using PHP?

Hey there, so I'm pretty new to PHP and I have a question. Is it possible to retrieve the input value from an existing input field on a page using PHP when the page loads, and then assign that value to a variable? For instance, let's say I have ...

Angular 5 Error Messages for HTTP Interceptors

I'm facing an issue regarding Angular 5: HTTP Interceptors. I am still new to this, so please bear with me as I grasp the concepts. Here is the error message that I encountered: compiler.js:19514 Uncaught Error: Provider parse errors: Cannot instan ...

Can React-Select be utilized in the browser directly from the CDN?

Is it possible to utilize react-select directly in the browser without using bundlers nowadays? The most recent version that I could find which supports this is 2.1.2: How to import from React-Select CDN with React and Babel? In the past, they provided r ...