Route Guard: How to make route guard true based on list sent by the server?

≯℡__Kan透↙ 提交于 2019-12-13 10:06:03

问题


I was trying to use route guard in my app that should let you go to a component only if the server sends you some parameters.

This is the list of the parameters that the server can send me (not all of them are sent each time)

  AGREEMENTS_VIEW 
  PROSPECTS_VIEW
  AGREEMENTS_INSERT_UPDATE
  PRODUCTS_INSERT_UPDATE
  PROSPECTS_INSERT_UPDATE
  DOCUMENTS_VIEW
  DOCUMENTS_INSERT_UPDATE

My route guard:

@Injectable()
export class UserRouteAccessService implements CanActivate {
    userActions=[];
    constructor(private router: Router, private securityService:CralSecurityService) {
     }
     securityActions(){debugger;
        this.securityService.securityActions().subscribe(
           (res: Array<actions>) => {
             this.userActions = res;
             console.log(res);

           });
       }


    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        this.securityActions();

        if (this.userActions = actions ) {
            return true;
        } else {
            return false;
        }
    }

Now how can I tell in the if that its true when some of the paramenters are sent or not? is userActions=[] correct? For example it should go to "true" when AGREEMENTS_VIEW PROSPECTS_VIEW are sent.

Also, is this ok?

export class actions{
          AGREEMENTS_VIEW :string;
          PROSPECTS_VIEW :string;
          AGREEMENTS_INSERT_UPDATE :string;
          PRODUCTS_INSERT_UPDATE :string;
          PROSPECTS_INSERT_UPDATE :string;
          DOCUMENTS_VIEW :string;
          DOCUMENTS_INSERT_UPDATE :string;
}

Http post:

securityActions(): <Array<any>> {
    return this.http.post<Array<any>>(
        `${this.ENDPOINT}/security-actions`,
        null,
    );
}

回答1:


The signature of the interface is as follows :

interface CanActivate {
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean
}

This means you can return an HTTP call that returns a boolean.

So you can write this :

authorized = [
  'AGREEMENTS_VIEW',
  'PROSPECTS_VIEW',
  'AGREEMENTS_INSERT_UPDATE',
  'PRODUCTS_INSERT_UPDATE',
  'PROSPECTS_INSERT_UPDATE',
  'DOCUMENTS_VIEW',
  'DOCUMENTS_INSERT_UPDATE',
];

securityActions(): Observable<boolean> {
  return this.securityService.securityActions().pipe(
    map(response => this.authorized.includes(response))
  );
}


canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
  return this.securityActions();
}


来源:https://stackoverflow.com/questions/51816933/route-guard-how-to-make-route-guard-true-based-on-list-sent-by-the-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!