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

Module is absent in JavaScript but present in TypeScript

As I delve into coding a vscode extension by following a tutorial, I encountered an issue with importing in my server.ts file. The directory structure looks like this: ...

Angular - Dropdown menu fails to display options

I encountered an issue with the JSON response from my Angular-12 API endpoint: { "message": "vehicle Model Detail.", "error": false, "code": 200, "results": { "vehiclemakes": [{ ...

ASP.NET is being used to host an angular application, but the deployUrl feature is

I have a .NET 6.0 ASP.NET application where I've set up a route /ngxapp to serve my Angular 13 application. The Angular app is stored in the wwwroot/ngxapp folder, as shown below. I've been using this code for years to deliver the Angular app: ...

Executing methods sequentially in the ngOnInit lifecycle hook consecutively

Working with Angular15 has presented me with a challenge. In my app.component.ts file, I have two methods: “ngOnInit()”, as shown below. public ngOnInit(): void { this.getToken(); this.UserLoggedIn(); } I am looking to run the above two functions in ...

What is the best way to eliminate the left margin entirely in CSS?

I am attempting to create an image view that fully covers the window, without any margins. I have tried various solutions such as setting the body margin and padding to 0, but they do not seem to work. body { margin: 0px; padding: 0px; } or *, html { ...

The default filter in Angular Material Autocomplete is failing to function as expected

I've implemented the Autocomplete feature from Angular Material in my project, but I'm facing an issue with the search filter. It seems that the default filter provided in the example is not working as expected – instead of filtering based on m ...

Error message: Object literal is limited to declaring existing properties

The source code was obtained from this Codesandbox demo: CodeSandbox - Cover Image Example Subsequently, an .eslintrc configuration file was generated with the following content (the only content present): { "extends": "react-app" } However, a TypeScri ...

Ways to retrieve the name of the chosen option from a dropdown menu

Is there a way to retrieve the text name of a selected dropdown value using a PrimeNG dropdown? Incorporating a PrimeNG dropdown: HTML <p-dropdown [options]="regionSelectList" [(ngModel)]="reg" [filter]="true" [ngModelOptions]="{standalone: true}"> ...

Typescript offers a feature where we can return the proper type from a generic function that is constrained by a lookup type,

Imagine we have the following function implementation: type Action = 'GREET' |'ASK' function getUnion<T extends Action>(action: T) { switch (action) { case 'GREET': return {hello: &a ...

The error message "Property 'data1' is not a valid property on the object type {}"

const Page: NextPage = ({data1}:{data1:any}) => { const [open, setOpen] = React.useState(false); const [data, setData] = React.useState(data1); const handleAddClick = () => { setOpen(true); }; ..... } export async function getServerS ...

magnify within a div with a set width

Looking for a way to make a div both zoomable and scrollable within a fixed-width container using transform: scale(aScaleRatio) for zooming in/out. Check out this demo for achieving the zoom effect. However, the inner div seems to have trouble aligning to ...

Accept only numerical input, any other type will prompt a notification

Ensuring that users can only input numbers is functioning properly. If a user attempts to enter anything other than a number, an error message should be displayed. I have experimented with Validators and patterns, but I am unable to get the error message ...

Typescript check for type with Jest

Assume there is an interface defined as follows: export interface CMSData { id: number; url: string; htmlTag: string; importJSComponent: string; componentData: ComponentAttribute[]; } There is a method that returns an array of this obj ...

Accordion symbol for adding or subtracting

Looking for a way to change the Toggle text in my angular 7 application accordion to images or content displaying a + sign for collapse and - for expand. I need to achieve this using CSS in my SCSS stylesheet so that I can later change the color of the sig ...

Identifying modifications within the @Input property in Angular 4

Can someone clarify how to detect changes in an @Input property within a component, rather than just when passed from its parent? I haven't found a clear answer to this yet. Thank you! ...

Unlocking the Power of Typescript and ReactJS: Maximizing Efficiency with Previous State

I'm encountering difficulties implementing the previous state in React 18 with Typescript version 4.8.3. Here is my refreshToken code and I'm receiving the following error: Value of type '(prev: any) => any' has no properties in c ...

Angular4 provider being integrated into an AngularJS application offers the provider functionality

I have recently migrated my app from AngularJS to Angular4. Now, I want to create a provider in Angular4 and inject it into the app.config in AngularJS. Here is what I currently have: import { UtilsService } from './../utils/utils.service'; imp ...

Is it feasible to programmatically define the onClick action for an element within a ReactNode?

Let's discuss a function called addAlert that adds messages to an array for display as React Bootstrap alerts. While most alerts are simple text, there's one that comes with an "undo the last action" link. The challenge is that when this "undo" l ...

Tips for accessing the value and text of an Angular Material mat-select through the use of *ngFor

When using a dropdown menu, I want to retrieve both the value and text of the selected option. View dropdown image Underneath the dropdown menu, I aim to display values in the format of "options: 'value' - 'selected option'". compone ...

Utilize a variable within an HTML attribute

Currently utilizing Angular and I have the following HTML snippet <input onKeyDown="if(this.value.length==12 && event.keyCode!=8) return false;"/> Is there a way for me to incorporate the variable "myNum" instead of the ...