Am trying to share json data from one component to another component (like parent to child) .using a service.I have two methods in this service one for setJsonData and other is getJson Data.
Service Class
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class XeproviderdataserviceService {
jsonData = {};
constructor() {
this.jsonData = {};
}
setXeProviderJson(val: object) {
this.jsonData = val;
console.log('setjson Data-', this.jsonData);
}
getXeProviderJson() {
return this.jsonData;
}
}
Parent Component
export class MainComponent implements OnInit {
active = 1;
constructor(private xeDataService: XeproviderdataserviceService) {
ngOnInit() {
}
selectTab(value, jsonData) {
this.active = value;
this.xeDataService.setXeProviderJson(jsonData);
console.log('getting', this.xeDataService.getXeProviderJson);
}
}
Child Component
import { Component, OnInit } from '@angular/core';
import { XeproviderdataserviceService } from '../xeproviderdataservice.service';
@Component({
// tslint:disable-next-line:component-selector
selector: 'xservice-tab-component',
templateUrl: './xeservice.component.html',
styleUrls: ['./xeservice.component.css']
})
export class XeserviceComponent implements OnInit {
constructor( xeDataService: XeproviderdataserviceService) {
console.log('get json Data', xeDataService.getXeProviderJson());
}
ngOnInit() {
}
}
Above code i can able to set data using setJsonData function.when i trying to getdata using getJsonData method it will get empty. i couldn't figure out what I am doing wrong..... in browser i can see like this
You can use Subject for this process it will emit the value for every event triggers. Very simple and important topic "Subject"
Parent component
In Your XeproviderdataserviceService Service..
Child Component