等到在 angular 中调用订阅

Wait until a subscribe is called in angular

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

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' } },

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

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

您可以将 canLoad 设为 return 布尔类型的 Observable (Observable<boolean>) 和 return 类似于 -

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

您可以将 canActivate 参数用于 route 来自 Core angular 的 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 是您获取当前登录用户的服务