0

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
    Do you want to persist the data in your application even if browser window is closed or what exactly are you trying to achieve? – Fabian Strathaus Sep 24 '22 at 06:18
  • @FabianStrathaus i try to send value between component to use it ; the result value change by page example on person has access to edit menu and use ngif(result==1 )but refresh make it undefined i don't want achieve it like localstroage – Majid Maddah Sep 24 '22 at 06:49

1 Answers1

1

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

Exception
  • 571
  • 1
  • 3
  • 15