路由卫士:如何根据服务器发送的列表使路由卫士为真?

时间:2018-08-13 07:12:12

标签: angular typescript post angular-route-guards

我试图在我的应用程序中使用路由防护,只有在服务器向您发送一些参数时,该路由防护才能让您进入组件。

这是服务器可以发送给我的参数列表(并非每次都发送所有参数)

  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时,它应该转到“ true”   已发送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;
}
  

Http帖子:

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

1 个答案:

答案 0 :(得分:1)

signature of the interface如下:

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