Is your Angular5 service failing to transmit data?

I have two components in my code, A and B. Component A contains a form with data that I want to send to component B. However, it seems like component B is not receiving any data.

Here is the code for Component A:

import { MyService } from 'path/myService.service';
@Component({
  //blah blah
  providers: [MyService]
})
export class ComponentA implements OnInit {

  //my form data

  constructor(private myServ: MyService) {}

  ngOnInit() {
  }

  onChange(event) {
    const data = event.target.value;
    this.myServ.changeMessage(data);
    console.log("sent");
  }
}

And here is the code for Component B:

import { Component, OnInit } from '@angular/core';
import { MyService } from 'path/myService.service';

@Component({
  // blah blah
  providers: [MyService]
})
export class ComponentB implements OnInit {

  recievedData = null;

  constructor(private myServ: MyService) {} 

  // i tried putting this in constructor instead, but it still didn't work
  ngOnInit() {
    this.myServ.currentMessage.subscribe(message => {
      console.log(message);
      this.recievedData = message
    });
  }
}

This is the code for My Service:

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

@Injectable({
  providedIn: 'root'
})
export class MyService {

  private messageSource = new BehaviorSubject(0);
  currentMessage = this.messageSource.asObservable();

  changeMessage(message) {
    this.messageSource.next(message);
  }

  constructor() { }
}

Although the console log displays "sent" when triggering the onChange method in Component A, the `console.log(message)` never shows up in the subscribe block of Component B. Any suggestions on why this might be happening?

Answer №1

In order to ensure that each component has its own instance of the service, you must provide MyService within the providers array in @Component. By removing providers from the component metadata, you run the risk of sharing a single instance across multiple components.

Answer №2

Whenever I have employed the BehaviorSubject, it has required me to subscribe to the observable, utilize the async keyword, and employ await on the response. In another component, you could implement it as follows:

this.toggleService.currentMessage.subscribe(async(message) => 
{
  this.recievedData = await message;
});

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

Discovering the root cause of why a particular CSS style is not being implemented correctly

Currently, I am in the process of developing a secondary theme for one of my websites. It's going to be a dark theme. I'm facing an issue where a specific CSS style is not being applied to a particular element, even though it works perfectly fine ...

Transforming javascript's array.map into php's array_map function

The following code snippet is written in JavaScript and consists of a hashmap array with keys and values. I have created a function using map that returns the values of the entered keys. var rule = { "c": "d", "a": "o", "t": "g", "h": "a", "e": "n", "n": ...

Learn how to create a "generated" texture coordinate in three.js similar to how it is done in Blender Cycles

How can I properly display a texture on a cylinder object using THREE.js without distortion? Currently, the texture appears stretched along the edges of the cylinder as shown here: https://i.sstatic.net/O2YFr.png This issue is based on the texture provide ...

Having trouble pushing to an array in Angular typescript? It seems to be returning as undefined

As a newcomer to Angular with a basic understanding of JavaScript, I am attempting to create a program that can solve Sudoku puzzles. In a 9x9 grid, there are a total of 81 points or squares. To efficiently check for violations of Sudoku rules - no repeati ...

Utilizing Vue.js to compare two arrays and verify if the results are identical

I am in the process of developing a theater app that requires me to work with JSON data consisting of two arrays: Sections and Groups. While I have successfully loaded both arrays into my Vue app, I now need to compare them to find matches. The first array ...

What is the process for creating a progress bar in PixiJS?

Can someone guide me on creating a progress bar similar to the one in PixiJS? Screenshot ...

Instructions on converting text to a Float value and displaying the calculated result in a separate div

I am attempting to extract a string from a div, clear its content, then retrieve the actual price from ".skuBestPrice", remove any special characters, perform calculations to convert it into a floating point number, and display this number in the div ".tot ...

My Discord bot seems to be malfunctioning and failing to send out

I am new to discord.js and I'm having trouble getting my bot to respond with a message when I send one on the server. The bot shows as online in Discord and "Logged in!" appears in the console when I run it, so client.on("ready") seems to be working f ...

Grunt Typescript is encountering difficulty locating the angular core module

Question Why is my Grunt Typescript compiler unable to locate the angular core? I suspect it's due to the paths, causing the compiler to not find the libraries in the node_modules directory. Error typescript/add.component.ts(1,25): error TS23 ...

How can Backbone.js utilize Ajax to bind data to a Collection?

I've recently delved into the world of Backbone.js. My goal is to create a Collection and populate it with data sourced externally. The current format of the data is CSV, not JSON. I am considering converting it to JSON for simplicity. Therefore, I ...

Ensuring a fixed table with vertical scrolling only, no horizontal scrolling, while scrolling in either direction

I'm working with an HTML fixed design that contains a center-aligned table with extensive data scrollable both vertically and horizontally. To address the issue of keeping column headers visible when scrolling vertically, I used jQuery's clone() ...

Tips for embedding a script snippet into an Angular HTML file

Incorporating Bootstrap tooltip in a component using CLI and Bootstrap: Take note that Tooltips need to be initialized with jQuery: <script> $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }); </script> W ...

Utilize the controller data to display information on a day-by-day basis

In my attempt to design a weekly calendar using AngularJS, I am facing challenges when it comes to inserting events into the 7 boxes representing each day of the week on the calendar. The current HTML structure is as follows: <div class="week"> ...

Steps to finish (refresh) a mongoDB record

Currently, I am dealing with the following scenario: An API request from one service is creating multiple MongoDB documents in a single collection. For example: [ {_id: 1, test1: 2, test: 3}, {_id: 2, test1: 3, test: 4} ] Subsequently, a second service ...

"afterAll encountered an error: [ErrorEvent object] was thrown" - Testing Angular 4 Components

During my work on Angular 4 unit tests, I encountered an error on one of the pages that utilizes Google Maps and the AGM package: An error was thrown in afterAll\n[object ErrorEvent] thrown Has anyone experienced this issue before and knows how to re ...

What kind of data does this collection hold, and what is the best method to retrieve its stored values?

I recently received a code to program a logic for and I have successfully figured out my algorithm. However, I am facing difficulty determining the datatype of a particular declaration. My task involves comparing the values of "skills" in each row to &apos ...

Leveraging the power of mapState and mapMutations within a namespaced module

I'm having trouble accessing mutations and states after dividing my Vuex store into three modules. I've attempted various syntaxes, but none seem to be working for me. MapStates: This is how I have set up the mapStates, with 'vendor' a ...

Encountering a TypeError with Arg 1 while trying to execute the save method in jsPDF

I am currently working on a react project with a simple implementation of jsPDF. I am trying to execute the sample 'hello world' code but encountering an error when using the save method: https://i.stack.imgur.com/o4FWh.png My code is straightf ...

Angular rxjs subscription error method not functioning as intended

I have a component that is making an HTTP request to a Node.js backend. The component is using a service without leveraging ngrx. The issue I am facing is that when I receive an error response from the backend, the code within the error method of the subs ...

Encountered an issue while attempting to make a GET request using the fetch API

Currently, I am attempting to retrieve some data from the server using react.js and the fetch API. However, I keep encountering this error: SyntaxError: Unexpected token < in JSON at position 0. This is the code snippet I am using to fetch the data: ...