Using a service to transfer data between components in an article.
Learn more about passing 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's data value can be either 1 or 0.
sender(data){
this.transfereService.setData(data);
}
Received component:
ngOnInit() {
this.data= this.transfereService.getData();
}
When changing the page in HTML, users gain access to some menu based on data being equal to 1.
However, there is a problem - when refreshing the page, the data value becomes undefined. How should I handle this?