首页 > 解决方案 > 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 调用,我将获得标头值。如何重构代码并接收标头值。

标签: angulartypescriptrxjs

解决方案


在我使用 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的文档

和 -> Access-Control-Expose-Headers 的完整解释


推荐阅读