带有 ASP.NET Web Api 2 的 angular4 防护的解析器
resolver with a guard in angular4 with ASP.NET Web Api 2
我正在 angular 4 项目 Asp.NET Web API 2. 我想在用户进入管理部分之前检查他是否被授权。
我试图在 angular 的路由中设置解析器,像这样:
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
return this.profile.getProfile()
.map(result => { setAuthorized(); return result;})
.catch(res => { return Observable.of(new Profile()); });
}
setAuthorized() 函数将在全局变量中设置授权,以便可以使用函数 isAuthorized() 进行检查
和授权守卫:
if (this.route.firstChild != null) {
return this.route.firstChild.data.map( res => {
if (isAuthorized()) {
return true;
}
});
} else {
return Observable.of(false);
}
路由是:
const routes: Routes =
[
{path: ':lang', component: LanguageComponent,
children: [
{ path: 'dashboard', component: DashboardComponent, resolve: { authority: AuthorityResolverService} },
{ path: 'admin', component: AdminComponent, canActivate: [AuthorizedGuard], resolve: { authority: AuthorityResolverService}},
]}
];
似乎一切正常。但问题是,当我单击 F5 或复制 URL 并在新的 window 中打开它时,我总是会被重定向到错误页面。当我监控工作流程时,它显示当我试图直接到达 URL 时它没有调用解析器:
localhost/admin
我没有收到任何错误,但我总是被重定向。
有什么想法吗?
这是预期的行为。当你命中路线时,守卫将首先是 运行,如果 canActivate
return 为真,那么解析器将是 运行。由于您的 guard
将 return 为假,您的解析器将不会被调用(也不应该被调用)。
这意味着您可能想要重新设计您的逻辑,将 profile/authorization 放入守卫中,因为这才是真正的守卫:它应该检查某些条件并根据它解决。您的条件是用户已通过身份验证,因此属于守卫。
解析器的目的是在允许用户激活组件后获取组件所需的数据。
我正在 angular 4 项目 Asp.NET Web API 2. 我想在用户进入管理部分之前检查他是否被授权。 我试图在 angular 的路由中设置解析器,像这样:
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
return this.profile.getProfile()
.map(result => { setAuthorized(); return result;})
.catch(res => { return Observable.of(new Profile()); });
}
setAuthorized() 函数将在全局变量中设置授权,以便可以使用函数 isAuthorized() 进行检查 和授权守卫:
if (this.route.firstChild != null) {
return this.route.firstChild.data.map( res => {
if (isAuthorized()) {
return true;
}
});
} else {
return Observable.of(false);
}
路由是:
const routes: Routes =
[
{path: ':lang', component: LanguageComponent,
children: [
{ path: 'dashboard', component: DashboardComponent, resolve: { authority: AuthorityResolverService} },
{ path: 'admin', component: AdminComponent, canActivate: [AuthorizedGuard], resolve: { authority: AuthorityResolverService}},
]}
];
似乎一切正常。但问题是,当我单击 F5 或复制 URL 并在新的 window 中打开它时,我总是会被重定向到错误页面。当我监控工作流程时,它显示当我试图直接到达 URL 时它没有调用解析器:
localhost/admin
我没有收到任何错误,但我总是被重定向。 有什么想法吗?
这是预期的行为。当你命中路线时,守卫将首先是 运行,如果 canActivate
return 为真,那么解析器将是 运行。由于您的 guard
将 return 为假,您的解析器将不会被调用(也不应该被调用)。
这意味着您可能想要重新设计您的逻辑,将 profile/authorization 放入守卫中,因为这才是真正的守卫:它应该检查某些条件并根据它解决。您的条件是用户已通过身份验证,因此属于守卫。
解析器的目的是在允许用户激活组件后获取组件所需的数据。