Passing information between components in Angular 2 using a shared service

After capturing data from one component, I am attempting to transfer it to another component through a service.

Component1 (Start) : radio box View

                <md-radio-button
                    *ngIf="item.id===1"
                    value="{{item.value}}"
                    class="{{item.class}}"
                    checked="{{item.checked}}"
                    (click)="onSelectType1(item)"> //capturing the value here
                {{item.label}}
            </md-radio-button>

ts code

public  onSelectType1(selected:any){
        this.formeService.type1Change(selected.nb)
}

SERVICE :

@Injectable()
export class FormeService{
public type1S : any;

public  type1Change(selected):any

{

    this.type1S=selected;  //storing it in the service here

 }

Component 2 : (End) : Simple View

ts code

export class ContentComponent{

constructor(public BackService : BackgroundService ,
                public formeService: FormeService)
    {
        console.log(this.formeService.type1S) 



////// displays as undefined in the console !!!!!!!!!!!!!!!!! 


The issue lies HERE: how can I access the value of my variable in this section?



}

!!!!!!!! and meanwhile in the view it shows me the value:

{{formeService.type1S}}  // normal functionality here

Can someone advise on how I can display the data value in the "end component ts code"?

Answer №1

Here's a complete example with a Plunker

import {Injectable, Component, Directive} from 'angular2/core'
import { BehaviorSubject } from 'rxjs/subject/BehaviorSubject';
import 'rxjs/Rx';

@Injectable()
export class DataService {
  public dataStream$:BehaviorSubject<number> = new BehaviorSubject<number>(null);

  // notify subscribers when new values are set
  set data(value:number) {
    this.dataStream$.next(value);  
  }
}

@Component({
  selector: 'content-comp',
  template: `
<div>{{value}}</div>
`})
export class ContentComponent {
  value:number;

  constructor(public dataService: DataService) {
    // subscribe to updates
    this.dataService.dataStream$.subscribe(val => {
      this.value = val;
    });
  }
} 

@Component({
  selector: 'other-comp',
  template: `
<button (click)="clickHandler()">update counter</button>
`})
export class OtherComponent {
  counter:number = 0;
  constructor(private dataService: DataService) {}

  // update the counter      
  clickHandler() {
    this.dataService.data = this.counter++;
  }
} 

@Component({
  selector: 'my-app',
  providers: [DataService],
  directives: [ContentComponent, OtherComponent]
  template: `
  <h2>Hello {{name}}</h2>
  <content-comp></content-comp>
  <other-comp></other-comp>
`
})
export class App {

}

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

"Learn how to automatically limit date selection to a maximum of 3 days after choosing a date with the nb-rangepicker rangep

I have successfully implemented the nebular date range picker to filter data. However, I am facing an issue with setting the default maxDate 3 days after selecting the input. I have tried multiple methods but none have worked for me. Below is my TypeScript ...

Decorators are not allowed in this context, the Angular component constructor may not include them

Currently working on developing a dialog component in Angular 17 using Angular Material 17 Encountering an issue inside the constructor of the dialog component where utilizing the @Inject decorator as shown in the official documentation example is not pos ...

Tips for utilizing express in your typescript projects

I'm curious about the transition of definition files from tsd to typings, and now to @types. How can I incorporate @types in a node/express project? What is currently preferred and what's the reason for moving from tsd to typing and finally to @t ...

'The object of type '{}' does not support indexing with a 'string'

I am currently working on a React component that dynamically generates an HTML Table based on an array of objects. The columns to be displayed are specified through the property called tableColumns. While iterating through the items and trying to display ...

Combining Power BI with Spring Angular for Seamless Integration

I am in the process of building a web platform with Spring and Angular. One important element I want to include is Power Bi integration, allowing me to generate datasets and reports using Spring and display charts in Angular. Are there any resources or t ...

Ensuring proper validation of sinon stub parameters in TypeScript

One of the unit tests in my code is responsible for checking the function arguments. it('Should retrieve product from the database', () => { stub(ProductModel, 'findById').returns({ lean: stub().returns({ total: 12 }), }); ...

Encounter a Typescript error when dealing with "app.ws" while using express-ws

I have a small project in mind where I want to create a BabyCam that can be accessed from any web browser using a Raspberry Pi Zero. My plan is to set up a web socket using express-is to stream video to multiple clients. I'm utilizing the raspivid-str ...

Encountered difficulty locating the module path 'stream/promises'

When importing the following in a typescript nodejs app import { pipeline } from "stream/promises"; Visual Studio Code (vscode) / eslint is showing an error message Unable to resolve path to module 'stream/promises' https://i.sstatic. ...

Can you explain the significance of 1x, 3x, etc in the Karma code coverage report for Angular unit testing?

I am a beginner when it comes to Unit Testing in Angular. Recently, I set up karma with code coverage using angular-cli. After running the command ng-test, I checked out the code coverage report and noticed references like 1x, 3x, etc. next to my code line ...

Embracing the power of Typescript with Node and Express?

While trying out the TypeScript Node Starter project from Microsoft, I found myself intrigued. Is it really possible to use TypeScript instead of Node on the server? There are a number of server-side tasks where TypeScript excels: - Building a web API ser ...

Organizing Array Elements in Sequence with Various Data Types Using Typescript

I'm working with an array that contains various data types - String, Number, and Boolean. My goal is to ensure that these elements are present in the array in a specific order. Here is how my array looks: const idList: (String| Number | Boolean )[] = ...

Setting up the view for 2-factor authentication in Umbraco 10: A guide for Angular or C# users

In my efforts to customize the two-factor authentication view for users with 2FA enabled in Umbraco, I've created a provider called UmbracoUserAppAuthenticator and used builder.Services.Configure to add the 'SetupViewPath', which is function ...

Errors caused by Typescript transpilation only manifest on the production server

During the process of updating my node version and dependencies on both machines, I came across an issue where building my app in production on one machine resulted in an error, while building it on my main machine did not. I found that the errors disappe ...

rxjs iterates through an array executing each item in sequential order

Is there a way to make observables wait until the previous one has completed when they are created from an array? Any help is appreciated! export class AppComponent{ arr: number[] = [5, 4, 1, 2, 3]; fetchWithObs() { from(this.arr) ...

Unable to access structuredClone on the global object within a Node.js application

structuredClone is causing issues in my NodeJS application. Whenever I try to utilize it, I encounter the error: structuredClone is not defined nodejs. To troubleshoot, I created a simple file and executed the following: console.log({ globals: Object. ...

Tidying up following the execution of an asynchronous function in useEffect

Recently, I've been facing a challenge while migrating a React project to TypeScript. Specifically, I'm having trouble with typing out a particular function and its corresponding useEffect. My understanding is that the registerListener function s ...

The combination of MUI pickers and date-fns led to a TypeError: the function utils.getYearText is not defined

In my latest project, I'm utilizing Material-UI V4, Material-UI Date/Time Pickers, and date-fns. The page design is minimalistic, and I have incorporated the DateTimePicker component from Material UI: <DateTimePicker label ...

Connecting to Multiple Databases in NestJS with MySQL Without Defining Entities

If you're interested in learning about connecting to MySQL using TypeORM and defining Entities, the NestJS documentation has all the information you need. In a situation where you have to connect to a MySQL server with multiple databases and need to ...

Unusual problem with [(ngModel)] not updating after Apollo subscription

I've encountered a strange issue with [(ngModel)] while working on an Angular 5 project. I have set up a form with inputs that successfully connect to the database using Apollo for sending GraphQL queries and mutations. The issue arises in editing set ...

Modifying preset values in settings.json within the [Extension Development Host] environment

Currently, I am developing an extension in VS Code and I want to implement a feature where a pop-up with a text message input appears when the extension first runs. The user input from the pop-up will be used to modify the default settings in the settings. ...