简体   繁体   中英

Compare values when object not received (TypeScript, Aurelia)

I'm trying to compare defined role (in my app.ts ) and revived role from WebServer . But when I'm not logged I have problem with compare values:

This is what I'm doing:

export class RoutingAuthorizeStep {

 public readonly userIdentity: UserIdentityModel;

 constructor (userIdentity: UserIdentityModel) {
    this.userIdentity = userIdentity;}

  run(navigationInstruction: NavigationInstruction, next: Next) : Promise<any> {

  let requiredRoles = navigationInstruction.getAllInstructions()
                    .map(i => i.config.settings.roles)[0] as string[];
                    //requiredRoles is example 'superUser'

  let isUserInRole = requiredRoles?
    requiredRoles.some(r => r === this.userIdentity.role) : true;
  }
 }

When I checked into debug: console.log(this.userIdentity.role);

I have this message:

aurelia-logging-console.js?dc89:45 ERROR [app-router] TypeError: 
                                                  Cannot read property 'role' of undefined
at RoutingAuthorizeStep.run (routing-authorize-step.ts?008f:30)
at next (aurelia-router.js?e32b:433)

I'm not an Aurelia dev but this seems like a simple JS problem unless i'm wrong. assuming the error is in the "isUserInRole" you could do this.

  let isUserInRole = requiredRoles?
    requiredRoles.some(r => this.userIdentity && r === this.userIdentity.role) : true;
  }

Basically just check if your userIdentity exists before checking its role.

Hope this helps!

I resolve it in this why:

 run(navigationInstruction: NavigationInstruction, next: Next) : Promise<any> {
  if (this.userIdentity == null)
  {
    //return to login
  }
  else
  {
     let requiredRoles: string;
     requiredRoles = navigationInstruction.getAllInstructions()
                                          .map(i => i.config.settings.roles)[0];    
      if (requiredRoles === this.userIdentity.role)
       {        
        return next();
       }
        //return to login
   }
}

It's working. But still requiredRoles.some is problem - maybe some library is missing .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM