1

I want to watch local storage but I am unable to write code

my scenario is when user is logged in I am getting user role id and permission list, depeds on permission only side menu is buit ,after login user can switch role, in that case side menu will change accordig to the permission, Here I save role id val in localstorage, when user is switching role role id is changing and permission also changed,

My doubt is how to watch this changes,

I followed this link How can I watch for changes to localStorage in Angular2?

But I am unable to write my scenario, Please help me

My code for reference

 constructor(public http: Http,public MenuService:MenuService) {
this.userroleId =  localStorage.getItem("roleId")
}

 getSideMenu () {
if( this.userroleId == 1) {
  this.MenuService.getAdminMenu().subscribe(menuItems => this.menuItems= menuItems, error => console.log(error));
}

if(this.userroleId == 2){
  this.MenuService.getpractitionerMenu().subscribe(menuItems => this.menuItems= menuItems, error => console.log(error));
  console.log('ss')
}
Community
  • 1
  • 1
Runali
  • 332
  • 1
  • 4
  • 17

1 Answers1

0

I would suggest you skip the localStorage and move over to use a service instead. So something like the following:

@Injectable()
export class Service {

  private userroleId = new Subject<string>();
  userRole = this.userroleId.asObservable();

  roleReceived(role: string) {
    this.userroleId.next(role);
  } 
}

this handles the changes to the role and the components using this service will subscribe to these changes. So where you want to set the role, do this:

emit(value: string) {
    this.service.roleReceived(value); // push the new role to service
}

and where you need to subscribe to the role, add the following in the constructor of that component:

service.userRole.subscribe(role => {
  this.role = role; // store the role in a variable
  getSideMenu(this.role) // check the role and render view accordingly!
})

now whenever changes are made for the role, since this component is subscribing to the changes, the role gets updated dynamically. So here you can use the functions that determine what view is to be shown.

Last, a simple example of the above in a child - parent context, with just hiding/showing div to simulate the view change. You would of course need to make the changes to fit your use case. Plunker

AT82
  • 71,416
  • 24
  • 140
  • 167