繁体   English   中英

等到在 angular 中调用订阅

[英]Wait until a subscribe is called in angular

早上好,我创建了一个 angualr 应用程序,我需要检查用户在路由中的角色。 我使用 canLoad 方法创建了一个服务“RoleGuardService”,该方法读取 JWS 令牌并检查用户权限:

import * as JWT from 'jwt-decode';
...
   const tokenPayload: App = JWT(token);
   if(tokenPayload.UserType == expectedRole){
      return true;
   }
   return false;

到目前为止一切顺利,但这迫使我声明硬编码的权限:

{ path: 'xxx', component: yyy, canLoad: [RoleGuardService], data: { expectedRole: 'Admin' } },

是否可以直接从 web API 创建需要授权的方法? 喜欢:

    var isAllowed = false;
    this.http.get('https://xxx/check_user/').subscribe(result: bool) => {
        isAllowed = result;
    }
    ///wait until the subscribe is called
    return isAllowed;

您可以将canActivate参数用于来自核心 angular 的路由,该路由是为该类型的用例https://angular.io/api/router/CanActivate 创建

示例:

  {
    path: 'protectedRoute',
    component: SecureComponent,
    data: {
      authorities: ['ROLE_ADMIN'],
    },
    canActivate: [UserRouteAccessService]
  }





@Injectable({ providedIn: 'root' })
export class UserRouteAccessService implements CanActivate {
  constructor(
    private router: Router,
    private accountService: AccountService,
  ) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    const authorities = route.data['authorities'];
    return this.accountService.identity().pipe(
      map(account => {
        if (!account) {
          return false;
        }

        if (!authorities || authorities.length === 0) {
          return true;
        }

        const hasAnyAuthority =   authorities.some((authority: string) => account.authorities.includes(authority));
        if (hasAnyAuthority) {
          return true;
        }
        this.router.navigate(['accessdenied']);
        return false;
      })
    );
  }

}

其中 AccountService 是您获取当前登录用户的服务

您可以使 canLoad 返回 boolean 类型的 Observable ( Observable<boolean> )并返回类似 -

return this.http.get('https://xxx/check_user/').map(result => result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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