transfer data between component to another component make data undefined

Viewed 31

i use service to transfer data between component from article

How to pass data between two components in Angular 2

export class SendService {
  constructor(
    private router:Router,
  ) { }
  private data;
  setData(data){
    this.data = data;
  }
  getData(){
    let temp = this.data;
      this.clearData();
    console.log('result is ',temp);
    return temp;
  }
  clearData(){
    this.data = 0;
  }

sender component data value = 1 or 0

  sender(data){
    this.transfereService.setData(data);
  }

Received component

  ngOnInit() {
    this.data= this.transfereService.getData();
  }

when change the page in html by component user get access to some menu by data= 1

but the problem is when refresh the page, data value = undefined ; what should I do ?

1 Answers

see, once you reload the page everything will go. so the data variable will be undefined. in your service, you're declaring the data variable but not assigning anything to it. to avoid an undefined issue just initialize that variable just like below.

export class SendService {
  constructor(
    private router:Router,
  ) { }
  private data = 0; //changed line
  setData(data){
    this.data = data;
  }
  getData(){
    let temp = this.data;
      this.clearData();
    console.log('result is ',temp);
    return temp;
  }
  clearData(){
    this.data = 0;
  }

here I'm providing a local storage concept example to achieve your solution. by using local storage you can have your values on reload too. this is just an example - stackblitz for local storage example

Related