Angular how to get headers value in the canActive function?

后端 未结 1 1436
猫巷女王i
猫巷女王i 2020-12-12 02:11

I need to redirect into different user page depends on the userRole value received from the header.

angular.routing.ts

{ path: \'\',         


        
相关标签:
1条回答
  • 2020-12-12 02:51

    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);
    }
    

    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

    By default, only the 6 CORS-safelisted response headers are exposed:

    Cache-Control
    Content-Language
    Content-Type
    Expires
    Last-Modified
    Pragma
    

    Now, You can access them in Angular.

    You can observe the full response, to do that you have to pass observe: response into the options parameter

    try this:

    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);
            })
        );
    }
    

    And finally this is the result:

    server: Kestrel
    content-type: application/json; charset=utf-8
    roles: Admin,User,Editor
    

    See this-> HttpClient's documentation

    and -> complete explanation of Access-Control-Expose-Headers

    0 讨论(0)
提交回复
热议问题