Route Guard: How to make route guard true based on

2019-09-20 18:18发布

问题:

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();
}