Having trouble with retrieving data from the service as expected

To facilitate the transfer of data between components, I implemented a service:

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

@Injectable()
export class DataTransferService {

  private messageSource = new BehaviorSubject<string>("hello");
  currentMessage = this.messageSource.asObservable();

  constructor() {
  }

  changeMessage(message: string) {
    this.messageSource.next(message);
    console.log(message);
  }

}

I have created a string variable called messageSource to store the data being passed and currentMessage as an Observable. Additionally, I have included a function to update this data.

Now, in the ngOnInit() method within one of my components, I wrote:

this.data.currentMessage.subscribe(message => this.message = message);

and declared a variable message:string within the component to hold the message.

Within a function, I have added:

selectNews(news) {
  this.data.changeMessage("hello3"); // test string
}

Following this, I want to access this string in another component.

Once again, in the ngOnInit(), I executed the same line of code and defined the message. However, the console log shows the string before the function has completed its action....

So where could the problem lie?

Edit Fiddle with complete code :

https://jsfiddle.net/fywdzz51/

Answer №1

By offering the service individually for each component, multiple instances are created within each component. To improve efficiency, consider providing the service in a centralized location for the entire module.

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

Determine the index of a specific character within a string using a "for of" loop

How can I obtain the position of a character in a string when it has been separated programmatically using a for...of loop? For instance, if I wish to display the position of each character in a string with the following loop: for (let c of myString) { ...

What is the reason behind the fact that the "transform" property of document.getElementById().style.transform="translateX()" only translates the element once?

I'm currently in the process of developing a new online game. With just a simple click of a button, my goal is to have the red square move horizontally by 50 pixels. Here's a snippet of the HTML code: <!DOCTYPE html> <html> <hea ...

Continuously update scrolling functionality

Could you please provide more information about the solution mentioned in the following question? I am facing a similar issue. jQuery’s css() lags when applied on scroll event Regarding solution #3 ->> To ensure continuous updates, it is suggeste ...

Obtaining req.body twice while handling a 307 redirect in an Express application

I have encountered a unique issue with my form submission in an express js application. Upon form submission, data is being POST to another route and then redirected back to the original route. View <form action="action" method="post> <input t ...

Avoid having Vue CLI delete all files in the dist folder

As I work on my Vue project, I am facing a challenge in syncing the dist folder with Git. Previously, this process ran smoothly when using webpack. However, after transitioning to @vue/cli and creating my project with vue create myProject instead of vue in ...

Displaying a progress bar while fetching data in Vue: A step-by-step guide

I am working on developing a progress bar using vue js and bootstrap for my desktop application. Within the template, I have the code that will generate the necessary markup: <div class="container-fluid p-0 vh-100" v-if="isLoading&quo ...

What steps can be taken to address the JavaScript error that states: Error : TypeError: $("j2t-temp-div").down(".j2t_ajax_message") is not defined?

If you want to see the issue in action, please visit this link. To replicate this error, choose a "Color" and "Size", then click "Add to Cart". While the "loading..." dialog box is still visible, click on the shade to close it. Quickly click on any other ...

The specified userID cannot be located within the array of objects

Trying to understand a tutorial on nodejs and expressjs that teaches how to implement user permissions on routes. However, I'm facing issues with a simple middle ware function designed to set the req.user as it keeps showing up as undefined. Below is ...

Show JSON array items

My php file (history.php) generates a JSON object $i=1; $q=mysql_query("select * from participants where phone='".mysql_real_escape_string($_GET['phone'])."' limit 10"); while($rs=mysql_fetch_array($q)){ $response[$i] = $rs[&ap ...

Instructions on creating a Superfish menu with a vertical layout in the first level and a horizontal layout in the second level

Currently, I am using the Superfish menu in Drupal7 and have designed my first item level to be vertical. However, I now want to style my second item level horizontally. I have tried various CSS approaches and added some class names via jQuery like $(&apo ...

Preventing the default behavior using event.preventDefault() does not seem to be effective when submitting a

Why is the event.preventDefault() method not functioning properly? <script type="text/javascript" src="vue.js"></script> <div id="app"> <form v-on:submit.prevent="saveData"> <input type="text" name="test"> <button ...

What is the best way to make an HTML form show fields depending on certain conditions?

Initially, I created an index page containing a form with various fields. The utility was built to handle all the fields, but now there's been a change in requirements. What I need is for only the Controller Type and Test Type fields to be displayed f ...

Utilizing the setNetWorkConditions function in webdriverjs for Chrome

Is there a way to properly utilize the webdriverjs setNetworkConditions() method as outlined in the official documentation? This is what my code looks like: const chromeCapabilities = webdriver.Capabilities.chrome() const chromeOptions = { ...

Retrieve the customized attribute from the chosen option within the datalist

Is there a way to retrieve the custom attribute "location" of an option selected from a datalist and display it? I understand that for a select element we can use selectedIndex, but how can this be achieved with datalist? <!DOCTYPE html> <html&g ...

Obtaining the value with JQuery's .change() function

Currently, I am in the process of setting up dynamic drop-down selectors using JQuery. Despite being new to frontend development, I have encountered a challenge with retrieving the value of a dropdown once it has been changed using JQuery. The user flow I ...

Manipulate paths in JS/JQuery by dynamically adding parameters with an indefinite number of values

My JavaScript script relies on an AJAX call that adds a parameter to an HTML request, but I've encountered two issues. I'm struggling to find a straightforward method to retrieve the pathname with parameters. With pure JavaScript, location.path ...

Ways to generate arrays in Typescript

My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that ...

How can you retrieve the input value in JavaScript when the cursor is not focused?

Here is an input I am working with: <a-form-item label="user" :colon="false"> <a-input placeholder="user" name="user" @keyup.enter="checkUser"/> </a-form-item> Within my methods: chec ...

Angular - connecting a function directly

Is there any potential performance impact of directly binding a function in directives like ng-show in AngularJS? <div ng-show="myVm.isVisible()"> .... </div> // controller snippet (exposed through controllerAs syntax) function myCtrl (myServ ...

Using Node.js to implement GET, POST, and DELETE functionalities

I have embarked on the journey of learning Node.js and I find myself in a state of confusion. Could you please guide me on how to construct effective HTTP requests for the following scenarios: 1) Retrieve all galleries from the gallerySchema using a GET ...