Angular 如何在 canActive 函数中获取标头值? [英] Angular how to get headers value in the canActive function?
问题描述
我需要重定向到不同的用户页面,这取决于从标头收到的 userRole 值.
I need to redirect into different user page depends on the userRole value received from the header.
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 调用,用于从服务器获取标头详细信息.
Initially I'm redirecting into LoginComponent, CanActive random.guard.ts is a API call to get the header details from server.
random.guard.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);
})
);
}
loginservice.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 调用,我将获得标头值.如何重构代码并接收头值.
If i subscribe the http get call, i will get the header value. How to refactor the code and recieve he header value.
推荐答案
在后端我使用的是Web API CORE,看下面的API:
In the backend I'm using Web API CORE, look at the following 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
中,标题名称为我们想在客户端访问它们,它们是服务器,角色
Here, I add tow headers : the first one is Roles
with its values and the second one in Access-Control-Expose-Headers
with the name of headers that we want to access them in client-side that they are Server,Roles
默认情况下,仅公开 6 个 CORS 安全列表响应标头:
By default, only the 6 CORS-safelisted response headers are exposed:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
现在,您可以在 Angular 中访问它们.
Now, You can access them in Angular.
您可以observe
完整的响应,为此您必须将observe: response
传递到选项参数中
You can observe
the full response, to do that you have to pass observe: response
into the options parameter
试试这个:
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
参见这个-> HttpClient 的文档
and -> 完整解释访问控制公开标题
这篇关于Angular 如何在 canActive 函数中获取标头值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!