angular - Angular如何在canActive函数中获取标题值?
问题描述
我需要重定向到不同的用户页面取决于从标头收到的 userRole 值。
angular.routing.ts
{ path: '', pathMatch: 'full', redirectTo: '/login' },
{ path: 'user', loadChildren: './home/home.module#HomeModule', canActivate: [AuthGuard], data: { roles: Role.User} },
{ path: 'admin', loadChildren: './somemodule#SomeModule', canActivate: [AuthGuard], data: { roles: Role.Admin}},
{ path: 'login', component: LoginComponent, canActivate: [RandomGuard] }
最初我重定向到 LoginComponent,CanActive random.guard.ts 是一个 API 调用,用于从服务器获取标头详细信息。
随机守卫.ts
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.loginService.isHeader().pipe(
map(e => {
// the problem is e.headers.get('userRole') undefined
if (e.headers.get('userRole') === 'user') {
this.router.navigate(['/user']);
} else if(e.headers.get('userRole') === 'admin') {
this.router.navigate(['/admin']);
} else {
return true;
}
}),
catchError((err) => {
this.router.navigate(['/login']);
return of(false);
})
);
}
登录服务.ts
isHeader(): Observable<boolean> {
return this.http.get(`${environment.baseUrl}home/login`,{observe: 'response'}).pipe(
map((response: any) => {
return response;
// response i did't get header value
// how to receive header value on here
})
);
}
如果我订阅 http get 调用,我将获得标头值。如何重构代码并接收标头值。
解决方案
在我使用 Web API CORE 的后端,请查看以下 API:
[HttpGet]
[Route("admins/overview/{id}")]
public IActionResult GetOverview(int id)
{
var item = _adminService.GetOverviewById(id);
Response.Headers.Add("Roles","Admin,User,Editor");// Here we add the roles with its values to Header
Response.Headers.Add("Access-Control-Expose-Headers", "Server,Roles"); // specify the name of headers to access
return Ok(item);
}
在这里,我添加了两个标题:第一个是Roles
它的值,第二个Access-Control-Expose-Headers
是我们想要在客户端访问它们的标题的名称,它们是服务器,角色
默认情况下,仅公开 6 个 CORS 安全列表响应标头:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
现在,您可以在 Angular 中访问它们。
您可以observe
完整响应,为此您必须传递observe: response
到 options 参数
尝试这个:
isHeader(): Observable<boolean> {
return this.http.get(`${environment.baseUrl}home/login`,{observe: 'response', withCredentials: true}).pipe(
map((response: any) => {
// Here, resp is of type HttpResponse<Sth>.
// You can inspect its headers:
console.log(resp.headers.get('roles')); <-- Get Value of Roles
// And access the body directly, which is typed as MyJsonData as requested.
console.log(resp.body.someField);
})
);
}
最后是结果:
server: Kestrel
content-type: application/json; charset=utf-8
roles: Admin,User,Editor
见this-> HttpClient的文档
推荐阅读
- qt - 可以在vscode中调试qml吗?
- python - 从嵌套列表中减去列表
- reactjs - 在 React Redux 中加载 Spinner (Thunk)
- javascript - 达到 Discord 上的 webhook 限制后,如何自动删除旧的 webhook?
- html - 弹跳按钮
- ios - 单元格导航在 TEXTVIEW 区域中不起作用
- javascript - Vue Router 通用导航栏搜索
- laravel - \PhpOffice\PhpWord 问题将 HTML 转换为 DOCX
- javascript - React中图像的src参数的变量名
- java - 如何在springboot / java app中使用给定注释获取方法