I receive a role of a user from database after login. I have given a array of roles in the sidemenu components where different roles are given. Then I tried to check if the role I received from database is included in the roles array or not. If the role is included in the array of roles, then I tried to move that menu to a reconstructed sidemenu. I put the function in ngOnIt() so that it can be loaded immediate after the login But the function is not loading due to its asynchronus behavior. How can I solve this without using async await in angular?
menuItems = [
{
label: 'File Info',
subMenuItems: [
{
label: 'New File',
link: 'fileinfo/newfile',
roles: ['General'],
},
{
label: 'Search File',
link: 'fileinfo/searchinfo',
roles: ['User', 'General', 'Admin'],
}
],
isOpen: false
},
{
label: 'File Info Settings',
subMenuItems: [
{
label: 'Supplier Information',
link: 'supplierlist',
roles: ['User', 'General'],
},
{
label: 'File Owner',
link: 'fileownerlist',
roles: ['User', 'General'],
},
{
label: 'Purpose',
link: 'purpose',
roles: ['User', 'General'],
},
{
label: 'Filetype',
link: 'filetype',
roles: ['Admin'],
},
{
label: 'Against',
link: 'againstlist',
roles: ['User', 'Admin'],
},
],
isOpen: false
},
];
This is the original Side menu.
I tried to reconstruct the above given menuItems if the role of the user is included on the roles array. The function to reconstruct the side menu is given below:
this.service.getUserRoleFromLocalstorage().subscribe(role => {
this.userRole = role;
const newMenuItems: any = [];
this.menuItems.forEach((item) => {
const allowedSubMenuItems = item.subMenuItems.filter(i => i.roles.includes(this.userRole));
console.log(allowedSubMenuItems);
if (allowedSubMenuItems.length > 0) {
const newItem = { ...item, subMenuItems: allowedSubMenuItems };
newMenuItems.push(newItem);
}
});
this.menuItems = newMenuItems;
});
The function is used in ngOnInit() so that it works immediately after the login. But the function is not loading first time due to asynchronus behavior. When I reload the page then it works fine.