-1

我试图在我的应用程序中使用路由保护,它应该让你只有在服务器向你发送一些参数时才可以访问一个组件。

这是服务器可以发给我的参数列表(不是每次都发)

  AGREEMENTS_VIEW 
  PROSPECTS_VIEW
  AGREEMENTS_INSERT_UPDATE
  PRODUCTS_INSERT_UPDATE
  PROSPECTS_INSERT_UPDATE
  DOCUMENTS_VIEW
  DOCUMENTS_INSERT_UPDATE

我的路线守卫:

@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;
        }
    }

现在,当某些参数是否发送时,我如何判断它是否为真?userActions=[] 正确吗?例如,当发送 AGREEMENTS_VIEW PROSPECTS_VIEW 时,它应该变为“真”。

还有,这样可以吗?

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

发帖:

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

1 回答 1

1

接口的签名如下:

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

这意味着您可以返回一个返回布尔值的 HTTP 调用。

所以你可以这样写:

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();
}
于 2018-08-13T07:22:02.507 回答