How can I retrieve header values in the canActivate function in Angular?

Depending on the value of userRole received from the header, I need to redirect to different user pages.

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] }

I am initially redirected to the LoginComponent. The RandomGuard calls an API to fetch the header details from the server.

random.guard.ts

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.loginService.isHeader().pipe(
        map(e => {
            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; 
        })
    );
}

To receive the header value, it is necessary to subscribe to the http get call and refactor the code accordingly.

Answer №1

Utilizing Web API CORE in the backend, take a look at this specific API:

[HttpGet]
[Route("admins/overview/{id}")]
public IActionResult GetOverview(int id)
{
    var item = _adminService.GetOverviewById(id);
    Response.Headers.Add("Roles","Admin,User,Editor");// Adding roles with values to Header
    Response.Headers.Add("Access-Control-Expose-Headers", "Server,Roles"); // Specify headers to access
    return Ok(item);
}

In this scenario, I include two headers: Roles containing its respective values and Access-Control-Expose-Headers indicating the names of headers we wish to access on the client-side, namely 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 retrieve them in Angular.

To observe the full response, ensure to pass observe: response into the options parameter like so:

isHeader(): Observable<boolean> {
    return this.http.get(`${environment.baseUrl}home/login`,{observe: 'response', withCredentials: true}).pipe(
        map((response: any) => {
           console.log(resp.headers.get('roles')); <-- Retrieving Roles value
           console.log(resp.body.someField); // Accessing requested body data type directly.
        })
    );
}

And here is the resulting header information:

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

Refer to HttpClient's documentation for more details.

Additionally, view the detailed explanation of Access-Control-Expose-Headers here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending information to the styles feature in Angular 2

Is there a way to transfer data from an Angular tag to the styles in the @Component? Take a look at my component: import { Component, Input } from '@angular/core'; @Component({ selector: 'icon', template: `<svg class="icon"> ...

A guide on implementing a "Select All" trigger in mat-select with Angular8/Material

Here is the code I have created: <mat-form-field appearance="outline"> <mat-label>Handler Type</mat-label> <mat-select multiple [(value)]="handlerType"> <mat-option *ngFor="let handler of handlerT ...

What is the best way to modify onClick events for elements in Ionic v4 with React?

Is there a way for me to interact with a button or IonItemSliding in order to alter the text or color of an element? <IonItemOptions side="start"> <IonItemOption color="success">Yes</I ...

Unraveling the Mystery of Dependency Injection: My Struggle to Grasp the Concept

Currently diving into Angular 2 and stumbled upon a video that really shed some light on the topic for me: https://www.youtube.com/watch?v=_-CD_5YhJTA However, when it comes to dependency injection, there's a particular point Mosh brings up at the 36 ...

Ensuring the completion of all validations in Angular 4

Currently, I'm working on a project that involves 3 FormControls. I am in need of a validation process that ensures either all three have values selected or none at all. Is there a method to achieve this type of validation? ...

Updating the navigation bar in Node/Angular 2 and displaying the sidebar once the user has logged in

I am facing a challenge with my first project/application built using Angular 2, particularly related to the login functionality. Here is what I expect from the application: Expectations: When I load the login component for the first time, the navbar ...

Exploring Angular 2's Internationalization Feature

After exploring the Angular 2 github repository, it's clear that numerous i18n features have been implemented. However, I'm struggling to find resources on how to actually use them. Is there any documentation or sample projects available that de ...

In order to emphasize the chosen list item following a component refresh

SCENARIO: Let's consider a scenario where I have a component named list, responsible for displaying a list of all customers. Within this list, certain conditions are set up as follows: 1) Initially, the 1st list-item (e.g. Customer 1) is selected by ...

The object prototype can only be an instance of an Object or null; any other value will

While attempting to create a codesandbox in order to replicate a bug, I encountered an additional issue. You can view my codesandbox here: https://codesandbox.io/s/vue-typescript-example-o7xsv The error message states: Object prototype may only be an ...

Stopping Angular 2 Service Request

I'm working on a menu with category tabs and the following function that gets triggered upon click. this._customerservice.GetCustomersByFilter(this.FilterOptions) //Get Customers by Page Number and CategoryId .subscribe(res => { ...

Update to using res.get() instead of res.getHeader()

Looking for assistance with the code snippet below: const compress = require('compression'); export const handleCompression = compress({ filter: function (req: express.Request, res: express.Response) { return (/json|text|javascript|css|fo ...

A step-by-step guide on how to access the version number in an Angular (v4+) application from the package

Currently, I am attempting to retrieve the version number of my Angular application from package.json where it is stored. Most resources recommend using require to load the JSON file like so: var pckg = require('../../package.json'); console.log ...

Storing string variables within an array and subsequently evaluating the similarity of each variable's value with those stored within the array

I am currently working on an Angular page which consists of input fields where I capture and store values in variables within the .ts file. The entered values are subject to change, so hard-coding them is not feasible. The variables that I use for storing ...

Encountered an error while trying to install Angular CLI using npm due to package.json with errno -

I attempted to install angular cli using npm. However, I encountered an error when running the command npm install -g @angular/cli. I am executing this command as a user, not as an admin. D:\AngularWorkstation>npm install -g @angular/cli npm WARN ...

Custom generator designed for projects with tailored ng/nrwl versions

Unfortunately, due to various reasons, we are unable to utilize angular version 12 at this time. As a result, we do not wish to use the current versions of ng and nrwl. I have been unable to find any documentation on how to generate a project with a speci ...

Angular and PrimeNG's P-dialog positioning feature seem to be having trouble coordinating effectively,

I've been attempting this with no success, utilizing Angular 8 and Primeng version 9.0.0-rc.4. Thank you for your help. <p-dialog position="right" header="Change Password" (visible)]="display"> Content </p-dialog> Check out more her ...

Tips for making use of incomplete types

Is there a way to reference a type in TypeScript without including all of its required fields, without creating a new interface or making all fields optional? Consider the following scenario: interface Test { one: string; two: string; } _.findWhe ...

What is the best way to dynamically update styleUrls or style properties in Angular?

One of my goals is to give users the ability to customize colors and certain styles within my Angular application. I am thinking about creating a structure like this: Structure: component-one   folder-with-css-files     style-for-component-1-fo ...

Is React 18 compatible with both react-redux and react-router?

At present, my react application is running on the following versions: react 17.0.x react-dom 17.0.x react-redux 7.2.x react-router-dom 5.x.x react-scripts 4.0.x redux 4.x.x My initial step towards upgrading to react@18 involved updating react-scripts to ...

Swagger Issue Resolved: Restriction on Number of Params Set

After setting up this option for my route, I noticed that when accessing the first parameter (page), it correctly returns the value entered in Swagger UI. However, when trying to access the second parameter (genre), it seems to interpret it as a string &ap ...