I have developed two components along with a shared service. My goal is to transfer data from one component to another, but I am encountering an issue where the object appears empty. Below is the code for the first 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() {
}
}
Below is the second component where the data from the first component needs to be passed. However, I am observing that the object in `this.myName` is empty.
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() {
}
}
Lastly, here is the shared service that facilitates communication between the two 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;
}
}