When canActivate returns false, the screen in Angular 2 will still be accessed

I am encountering a problem where my canActivate method is returning false, but still navigating to the blocked screen. This issue seems to only occur in Chrome, as everything works fine in IE. Here is how the canActivate method looks:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.getDataFromApi(state.url)
        .toPromise()
        .then(result => { 
            return result;
        });
}

Here is the getDataFromApi() method:

getDataFromApi(link): Observable<boolean> {
    return this.http.get("api/security")
                    .map(response => {
                        var url = link.replace("/", "");
                        var data = response.json();
                        var privileges = data["privileges"];
                        var currentItem = privileges[url];
                        return currentItem["view"];
                    });
}

Is there any solution to fix this Chrome-specific issue? Your help is greatly appreciated.

EDIT I have tested in IE, Edge, and Firefox where the issue does not occur. In Chrome, it only works when the developer console is open.

Answer №1

This issue appears to be related to asynchronous behavior.

Within your guard logic, you first return this.getDataFromApi(state.url), but then attempt to immediately return the result once it resolves with return result;. This means that your guard may return before the actual result is available.

I suggest creating a dedicated service for managing user authentication and state tracking. This service could include properties such as isLoggedIn: bool, roles: Role[], and more.

In your guard implementation, simply check with the service whether the user is isLoggedIn (or similar). If the user is authenticated, return true; otherwise, redirect them to a login page. Additionally, verify if the user has the required roles based on the information stored in the service before returning true or false.

For further insights, refer to the official documentation, which provides a detailed example of implementing this methodology.

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

Exploring how to read class decorator files in a Node.js environment

I've developed a custom class decorator that extracts permissions for an Angular component. decorator.ts function extractPermissions(obj: { [key: 'read' | 'write' | 'update' | 'delete']: string }[]) { re ...

Mysterious Error Retrieving /v2/me Endpoint from LinkedIn in Angular 11

My goal is to retrieve the r_liteprofile from LinkedIn using the Oauth2 3-legged flow. While it works perfectly in Postman, I keep encountering an 'Unknown Error' in Angular 11: Here's a snippet of the code: params = new HttpParams() .set(& ...

Vue is encountering difficulties resolving the index.vue file located in the parent directory

Having trouble importing a component from the path folder, I keep encountering an error message stating "Cannot find module './components/layout/Navbar'. Vetur(2307)". This is how I am attempting to import the component: import Navbar from "./c ...

Comparing tsconfig.json and tsconfig.build.json: what sets them apart?

Guides like those found at 1 and 2 often recommend having two separate files - tsconfig.json and tsconfig.build.json - at the root level of an NPM monorepo for TypeScript projects. What are the distinctions between these files? Is it possible to consolida ...

Response Looping Function

I am struggling with looping and storing data in an array. /** Model for displaying response*/ export class ResultsData { id: number, name: string, startDate: string, endDarte: string, startTime: string, ...

How can a class be imported into a Firebase Cloud function in order to reduce cold start time?

When optimizing cold start time for Firebase Cloud functions, it is recommended in this Firebase Tutorial to import modules only where necessary. But can you also import a class with its own dependencies inside a function? In my scenario, I need to use Bc ...

An array devoid of elements may still hold significance

I have a specific function structure as follows: public returnData(): { points: Array<{ x: number, y: number }>, pointsCount: Array<number> } { return { points: [{x: 0, y: 1},{x: 1, y: 2 }], pointsCount: [1, 2, 3, 4] } ...

Prisma designs a personalized function within the schema

In my mongo collection, there is a field named amount. My requirement is to have the amount automatically divided by 100 whenever it is requested. In Django, this can be achieved with a custom function within the model. Here's how I implemented it: cl ...

Dropdown with grouped options in Angular PrimeNG - displaying data other than the default label/value pair

Hello there, I've encountered some difficulties with the dropdown menu, specifically when it comes to organizing by groups. Initially, I faced challenges understanding the specific format required for the array used in options to populate the dropdow ...

Error: Unable to access postal code property since it is null in Angular 6

My application requires the user's firstName, lastName, email, mobile, and password. The User Account Information page should display fields such as firstName, lastName, mobile, gender, email, street1, street2, province, suburb, and postalCode. Howeve ...

What is the best way to transform an array of objects into a nested array through shuffling

I am dealing with a diverse array of objects, each structured in a specific way: data = [ { content: { ..., depth: 1 }, subContent: [] }, { content: { ..., depth: 2 ...

Facing a Bad Request error while trying to submit a Django Rest Framework Post request that appears to be valid, but is requiring a

Currently, I am in the process of creating a new instance of the SearchNeighborhood object and establishing a connection with an already existing SearchCity object through a POST request. The models I have set up are as follows: class SearchCity(models.M ...

What methods can I use to combine existing types and create a brand new one?

Is there a way to combine existing types to create a new type in TypeScript? `export type Align = 'center' | 'left' | 'right' export type Breakpoints = ‘sm’ | ‘md’` I want to merge the Align and Breakpoints types to ...

Angular v15 Footer Component Table

In my Angular 15 project, I am attempting to correctly position and utilize the mat table with the following code snippet: <tr mat-footer-row *matFooterRowDef="displayedColumns"></tr>. While the displayedColumns property is functionin ...

Streamlined Authorization in MEAN (SPA) Applications

I have created an application, but now I am trying to adapt it into a SPA application. The main issue I am facing is with the Authorization process. While I can successfully register new users, log them in, and retrieve their tokens, I seem to encounter a ...

Reset combobox to its default value when a different event happens

In my Angular 6 application, I have a reusable/shared component for a dropdown as shown below: <shared-dropdown-list-payments [valuesArray]="cashAccountLoaded" [defaultString]="defaultFromString" (outputEvent)="fromAccount($event)" tosca-id=" ...

NX - A comprehensive UI library featuring Storybook integration and individually exported components

As I delve into the world of Nx with Angular (fairly new to both), I am on a quest to create a component library that serves two main purposes: Capable of running Storybook Allowing components to be imported individually, rather than having to drag in the ...

When a React component in TypeScript is passed as a parameter and then assigned to a variable, an error with code TS2604 may occur stating that the JSX element type does not

I am currently facing an issue with handling props of a passed React Element in my Factory. I am getting a TypeScript error that says: TS2604: JSX element type 'this.extraBlock' does not have any construct or call signatures. This is my Child co ...

Encountering Gyp Errors During NPM Install in an Angular 5 Project

I encountered some gyp errors when trying to run "npm install" in my Angular 5 project. I'm not sure why these errors are occurring; perhaps someone here has seen similar issues before. https://i.stack.imgur.com/mMRO4.png I attempted various trouble ...

How to configure dynamic columns in material-table using React and TypeScript

My task involves handling a table with a variable number of columns that are generated dynamically based on the data received. To manage these columns, I have designed an interface that defines various properties for each column, such as whether it can be ...