【发布时间】:2018-07-11 06:53:27
【问题描述】:
我正在编写一个 Angular 服务来证明用户权限。在构造函数中,我想从 API 获取当前登录的用户。创建的当前用户用于本服务的其他方法。从组件调用此方法以检查可以显示哪些内容等。 问题是服务中的方法被调用的速度比当前用户可用的速度快。 有没有办法解决这个问题?
permission.service.ts
@Injectable()
export class PermissionService {
currUser = {
'id': "",
'permission': ""
};
apiService: AlfrescoApiService;
authService: AuthenticationService;
constructor(apiService: AlfrescoApiService, authService: AuthenticationService) {
this.apiService = apiService;
this.authService = authService;
this.init();
}
init() {
let userId: string = this.authService.getEcmUsername();
this.currUser.id = userId;
//API call
this.apiService.sitesApi.getSiteMember(SITENAME, userId).then(resp => {
this.currUser.permission = resp.entry.role;
})
}
isSiteManager(): boolean {
console.log(this.currUser.permission, this.currUser);
if(this.currUser.permission === "SiteManager"){
return true;
}else{
return false;
}
}
}
方法调用
export class AppLayoutComponent {
constructor(permissionService:PermissionService) {
permissionService.isSiteManager();
}
}
在谷歌浏览器中输出
{id:“管理员”,权限:“”}
id:“admin”权限:“SiteManager”
【问题讨论】:
-
the methods in the service are called faster than the current user is available- 您要查找的词是 asynchry ...即this.currUser.permission = resp.entry.role;是异步执行的,但您的代码表明您不知道这一点 -
是的,我知道它是异步的。但是我不知道如何解决这个问题。
-
这取决于你如何使用
isSiteManager()的结果以及应用程序是否使用Angular Router。
标签: javascript angular typescript asynchronous promise