How to load Appcomponent class before routing takes place

293 views Asked by At

I have set routing and display the page according to user roles. For this i am using guard on route. I am extracting userRole from service in Appcomponent class and using set and get method in main-service file. Now problem is that before i get role, routing takes place and it navigate to wrong url as it doesn't have role by then. Tough from next call, it works properly. Let me share the code:- 1.Here is guard class:-

export class HomeGuard implements CanActivate {
    constructor(private _router: Router,private mainService: MainService) {
    }
    canActivate(): boolean {
        let userRoles:any;
        alert('HomeGuard');
        userRoles = this.mainService.getSavedUserRole();
        //userRoles = ['Profile Manager','Operations','Shipper'];
        alert('userRoles are here'+userRoles);
        console.log('here in homeguard');
        if(userRoles) {
            if(userRoles.some(x => x === 'Shipper') || userRoles.some(x => x === 'Admin'))
                return true;
        }
        this._router.navigate(['/notfound']);
        return false;
    }
}
  1. Here is AppComponent where i am extracting userRole from service:-

    export class AppComponent {
      savedUserRoles:any;
      constructor(private translate: TranslateService,private mainService: MainService) {
          console.log('Environment config', Config);
          // this language will be used as a fallback when a translation isn't found in the current language
          translate.setDefaultLang(AppSettings.LNG_TYPE);
          // the lang to use, if the lang isn't available, it will use the current loader to get them
          translate.use(AppSettings.LNG_TYPE);
          this.mainService.getCurrentUser().subscribe(result => {
            this.savedUserRoles = JSON.parse(JSON.parse(result._body).Data).Roles;
            console.log('sdfghj'+this.savedUserRoles);
            this.mainService.setSavedUserRole(this.savedUserRoles);
          });
      }
    }
    
  2. Here is main-service where i have defined set and get method:-

    setSavedUserRole(name: any) { console.log('main'+name); this._userRoles = name; }

    getSavedUserRole() {
        return this._userRoles;
    }
    
0

There are 0 answers