Reputation: 71
I have created two components and one shared service, i want pass data from one component to another, but i am getting empty object bellow is 1st component
import { Component, OnInit } from '@angular/core';
import {SharedService} from './../shared.service';
import { Router, NavigationStart } from '@angular/router';
@Component({
selector: 'app-cone',
templateUrl: './cone.component.html',
styleUrls: ['./cone.component.css'],
providers: [SharedService]
})
export class ConeComponent implements OnInit {
req = <any>{};
constructor(public service:SharedService,private router:Router) { }
send(){
this.req.fname= "ketan";
this.req.lname= "pradhan";
this.service.saveData(this.req);
console.log('str');
this.router.navigate(['/apps/ctwo']);
}
ngOnInit() {
}
}
Bellow is the 2nd component where i need to pass the data from 1st comonent, i am getting empty object is this.myName
import { Component, OnInit } from '@angular/core';
import {SharedService} from './../shared.service';
import { Router, NavigationStart } from '@angular/router';
@Component({
selector: 'app-ctwo',
templateUrl: './ctwo.component.html',
styleUrls: ['./ctwo.component.css'],
providers: [SharedService]
})
export class CtwoComponent implements OnInit {
myName= <any>{};
constructor(public service:SharedService,private router:Router) {
this.myName=this.service.getData();
console.log(this.myName);
}
ngOnInit() {
}
}
Bellow is shared service which is for communicating between 2 components
import {Component, Injectable,Input,Output,EventEmitter} from '@angular/core'
// Name Service export interface myData { name:string, lname:string }
@Injectable()
export class SharedService {
sharingData: myData=<any>{};
saveData(str){
console.log('save data function called' + str.fname);
console.log(this.sharingData);
this.sharingData = str;
// this.sharingData.lname=str.lname;
console.log(this.sharingData)
}
getData()
{
console.log('get data function called');
return this.sharingData;
}
}
Upvotes: 1
Views: 319
Reputation: 73377
When you are setting providers
arrays at component level, it means that you have two separate instances of the service in this case.
You need to declare the service in your NgModule
providers
array instead, then the two components (and any other components in that module) will have the same instance of the service.
So remove the providers
arrays in your components, and instead add the service to providers array in your NgModule
.
@Component({
selector: 'app-ctwo',
templateUrl: './ctwo.component.html',
styleUrls: ['./ctwo.component.css'],
// providers: [SharedService] // remove these!
})
and instead....
@NgModule({
imports: [ ... ],
declarations: [ .. ],
bootstrap: [ ... ],
providers: [ SharedService ] // here!
})
Upvotes: 2