【发布时间】:2018-12-20 00:38:32
【问题描述】:
在调用 checkPermissions() 方法之前,我需要等到 getPermissions() observable 完成。但是对于我的生活,我无法得到它......
我也尝试过使用 async/await,但这似乎对我也不起作用?
我需要获得我的权限,然后才能检查它们,对吧。想法?
如果有更好的方法,我会全力以赴。
非常感谢。
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class RoleGuardService implements CanActivate {
constructor(public auth: AuthService,public router: Router) { }
canActivate(route: ActivatedRouteSnapshot): boolean {
//This will be passed from the route config, on the data property
const expectedRole = route.data.expectedRole;
var hasPerm = this.loadAndCheckPermissions(expectedRole);
console.log('done! ' + hasPerm);
return hasPerm;
}
loadAndCheckPermissions(expectedRole) {
var hasPermission = false;
localStorage.clear();
var myPermissions = localStorage.getItem('user-permissions');
if (myPermissions === null) {
console.log("PERMISSIONS from Server!");
//You can't wait for an Observable or Promise to complete.
//You can only subscribe to it to get notified when it completes or emits an event.
this.auth.getPermissions()
.subscribe(res => {
localStorage.setItem('user-permissions', JSON.stringify(res.body));
//Check permissions now
//hasPermission = this.checkPermissions(expectedRole);
});
} else {
hasPermission = this.checkPermissions(expectedRole);
}
console.log('loadAndCheckPermissions ' + hasPermission);
return hasPermission;
}
//Check a permission here
checkPermissions(expectedRole) {
return this.auth.checkPermission(expectedRole);
}
}
【问题讨论】:
-
loadAndCheckPermissions应该是可观察的,与canActivate相同。如果你有更高的函数依赖于它们返回的内容,你要么需要组合函数,要么继续将子函数声明为 observables
标签: angular observable