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
并具有我们要在客户端访问的头文件的名称,即它们是 Server ,角色
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
传递到options参数
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的文档
和-> 完整的说明Access-Control-Expose-Headers
这篇关于Angular如何在canActive函数中获取标头值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!