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;
}
}
providers
array of the parent of these components and then it will be shared by these two only – Anurag