2

I am a beginner for learning Angular 2 type script. I want to pass the data between one component to another component?

Serives.ts

    import {Component, Injectable} from '@angular/core';

    // Name Service
    export interface myData {
       myDataname:any;
    }

    @Injectable()
    export class GetService { 
        sharingData:any={myDataname:"My data string"}; 

        saveData(str:any){
            alert("Save Data");
        // console.log('save data function called' + JSON.stringify(str));
        this.sharingData.myDataname=str; 
        console.log(JSON.stringify(this.sharingData.myDataname));
      }
      getData():any{
     console.log('get data function called');
     console.log(JSON.stringify(this.sharingData.myDataname)+ "Get dats service s");
        return this.sharingData.myDataname;
}
    }

First Component.ts

import { GetService } from '../service/get-service';

    @Component({
      selector: 'firstcomponent,
      templateUrl: 'firstcomponent.html',
      providers:[GetService]
    })

    export class firstcomponentDetails {
    firstname:string;
    lastname:string;

      constructor(public getservice: GetService ) {
         this.getservice= getservice;

    submitForm(value: any):void{
            console.log(' Personal Details Form submited!');
        console.log(value);
        this.getservice.saveData(value);
    }
}
    }

Second Component.ts

 import { GetService } from '../service/get-service'; 
    @Component({
      selector: 'secondpage',
      templateUrl: 'secondpage.html',
       providers: [GetService],
    })
    export class SecondPage {
     getDatavaluesServices:any;
     constructor( public getservice:GetService){
    this.getservice = getservice;
     this.getDatavaluesServices=getservice.getData();
      console.log(this.getDatavaluesServices );
    }
    }

This is my code. I tried this code passing data first component to second component. I am getting to string value my data string. How to get first component value?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Peri
  • 158
  • 1
  • 4
  • 16

2 Answers2

2

You can create a service and import it into your main module and export it from there, then inject it into the components where you want to use it.

import { StateService } from '../../../core/state.service';

  constructor(
    @Inject(StateService) private stateSrvc: StateService
  ) {}

Your service will be something like this:

@Injectable()
export class StateService {
    someStateValue: string;;
}

This way you're creating a singleton service, meaning that there will be one instance of the service throughout the application, so any values you set from one component can be retrieved from another, allowing you to pass data back and forth between components without having rely on passing data via the URL and Router Params.

How you maintain the state storage in that service is up to you, you could simply declare variables as above and get and set values directly:

stateSrvc.someStateValue = 1234

or

someLocalVariable = stateSrvc.someStateValue

Or you can setup getVariable and setVariable functions in the service to have more control.

You can also make use of Observables and Subjects or BehaviorSubjects to store state using RxJS.

Stephen R. Smith
  • 3,310
  • 1
  • 25
  • 41
0

You should provide the service by the parent component or module to be sure only one instance is shared between components. Having providers:[GetService] on child components recreate the service when the componet is instantiated. Thus, you lose data set by the other component.

If you followed the guide Parent and children communicate via a service, you can see that children components don't have providers of the shared service on which communication is performed, but a parent mission-control component provides only one instance per every child such as my-astronaut.

In the mission-control template the my-astronaut component instantiated several times via *ngFor directive.

If it is not enough, you can create your own provider for the service using singleton pattern. (See also how it's implemented in this answer.) In this way using the provider you can provide the service to any component.

Roman C
  • 49,761
  • 33
  • 66
  • 176