Unexpected issue with Angular CanActivate: observable returning true, but failing on browser refresh

Our routing guard for CanActivate is functioning properly when navigating between links on the website. However, it fails when we do a full browser refresh, redirecting to the home page as if CanActivate returns false.

Here is the code for my guard:

@Injectable()
export class PermissionCheckGuard implements CanActivate {
    constructor(private userPermissionService: UserPermissionService) { }

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
    ): Observable<boolean> | Promise<boolean> | boolean {
        let permissionTag = route.data["permissionTag"] as string;

        let hasPermission$ = this.userPermissionService.hasPermission(null, SubjectType.Site, permissionTag, null);

        hasPermission$.subscribe(x => {
            console.log(x);
        });

        return hasPermission$;
    }
}

This is how I configured my router:

path: 'security/security-example', component: SecurityExampleComponent, canActivate: [PermissionCheckGuard], data: { permissionTag: 'Site_Permission_1' }

If relevant, here is the hasPermission function:

 public hasPermission(userId: string, subjectType: SubjectType, permissionTag: string, subjectId: string): Observable<boolean> {

        if (userId == null) {
            userId = 'Current';
        }

        const url = this.apiUrlBuilder.create('Security', 'Users', userId, 'Permission', {
            permissionTag: permissionTag,
            subjectType: subjectType,
            subjectId: subjectId
        });

        return this.http.get(url)
            .map<Response, boolean>((response: Response) => {
                return <boolean>response.json();
            })
            .catch((error) => {
                return this.errorHandlingService.ToNotification(error, this);
            })
    }

I have checked and ensured that the guard is returning an observable and the console log consistently displays true. Could this be an Angular issue or is there a mistake in my code?

Answer №1

It seems like the issue may have been resolved by the time you receive a response. Consider using the subject in this context.

import { Subject } from 'rxjs';

canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
    let permissionTag = route.data["permissionTag"] as string;

    let hasPermission$ = this.userPermissionService.hasPermission(null, SubjectType.Site, permissionTag, null);

 const subject: Subject<boolean> = new Subject();
    hasPermission$.subscribe(x => {
        console.log(x);
        subject.next(x);
    });

    return subject.asObservable();
}

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

How can I invoke the header component function in another component using Angular 2?

Is there a way to invoke the showmodel(displayType) function from another component? How can I call a function in the header component from a different component? header.component.ts import { Component,Renderer } from '@angular/core'; i ...

Blend multiple images using Angular

Is there a way to combine multiple images in Angular? I came across some HTML5 code that seemed like it could do the trick, but unfortunately, I couldn't make it work. <canvas id="canvas"></canvas> <script type="text/javascript"> ...

Can the type of an object be dynamically assigned in Typescript?

I keep encountering the eslint warning "@typescript-eslint/no-unsafe-assignment". This warning occurs when I am trying to extract specific keys and values from a variable that can be assigned objects of different types, with approximately 10 possible class ...

"Trouble with Typescript's 'keyof' not recognizing 'any' as a constraint

These are the current definitions I have on hand: interface Action<T extends string, P> { type: T; payload: P; } type ActionDefinitions = { setNumber: number; setString: string; } type ActionCreator<A extends keyof ActionDefinitions> ...

The paths configuration in tsconfig.app.json is not functioning as anticipated

Working with Angular to develop my website has been a rewarding experience. I am currently faced with the task of setting a BASE_API for my project, depending on whether it is in prod or dev> mode. To accomplish this, I have made necessary modifications ...

Is there a way to display the number of search results in the CodeMirror editor?

After conducting some research on how to integrate the search result count in Codemirror like the provided image, I was unable to find any solutions. I am currently working with Angular and utilizing ngx-codemirror, which led me to realize that editing the ...

Tips for utilizing the @Input() property of a component to set the initial value of an input field

Is there a way to utilize the value of an @Input() property on Component B as the initial value for an input field in that component when it is contained within Component A? I attempted passing the value during form construction, but found that it only wo ...

Storing information from JSON into an object

I am encountering an issue regarding transferring data from JSON to an object. Although this solution is functional, it is not entirely satisfactory. Take a look at the service. Is there an improved method for handling data conversion from this JSON to an ...

Remove the unnecessary space at the bottom of the Mat Dialog

I'm currently utilizing Angular Material within my Angular application. One issue I am facing is the excessive whitespace at the bottom of a dialog that displays information about a post. How can I reduce or eliminate this unnecessary space? Take a l ...

Struggling with getting Typescript async/await to function properly

I'm experiencing an issue with async/await in TypeScript targeting es2017. Here is the code snippet that's causing trouble: My route.ts : method: 'POST', config: { auth: { strategy: &apo ...

What causes the dispatch property to be undefined in a connected wrapped component within a connected Higher Order Component while using react-redux in conjunction with typescript?

As a new user, I am facing a particular challenge. I am working with a Higher Order Component (HoC) that injects properties into a wrapped component. The HoC itself returns a React.ComponentClass that is connected to the redux store with mapped and dispatc ...

In TypeScript, the function is failing to retrieve the complete array value

I'm facing an issue with a program that is supposed to piece together all the letters, but it's not functioning correctly. I've tried using the debugger, but it doesn't display any errors. Here's the code snippet: var phrase = [ &a ...

What changes occur to the files in an Angular project, specifically Angular 8, when the npm install command is run?

When running "npm install" in an Angular project (specifically angular 8), which files are created or modified? Do I need to delete the package.lock.json file along with the node_modules folder when updating something in the package.json file? Will npm i ...

Having trouble getting Jest transformers to play nice with a combination of Typescript, Webpack, and PEGJS

In my current NPM project: { "scripts": { "test": "jest --config=jest.config.js" }, "devDependencies": { "@types/pegjs": "0.10.3", "@types/jest": "29.1.1", ...

How do I steer clear of this nested subscription when working with Angular Material's dialog box?

This is my current setup: this.entitiesManagementService.searchAddressEventEmitter$.pipe(switchMap((_) => { const formValue = this.addressAttributesSearchForm.getRawValue(); return forkJoin([ this.entitiesManagementService.getAddressClassificati ...

Is it true that TypeScript prohibits the presence of circular references under the condition of having generic parameters

I encountered an issue of type error in the given code snippet Type alias 'bar2' circularly references itself.ts(2456) type foo = { bars: bar[]; }; //works fine type bar = foo; type foo2<T extends Record<string, unknown> = Record< ...

One way to conceal different sections of a Chart.js chart is by clicking on the legend

When using ChartJS, clicking on the legend will make the section disappear. Is it possible to reverse this behavior? For example, when clicking on the legend, all sections in the chart except for the clicked one should disappear. Does anyone have a sugge ...

Using variables in string interpolation

I have been attempting to showcase a react-table cell in a customized manner: public displayBooksTable() { return <div> <ReactTable data={this.props.books} columns={[{ column ...

Is it possible to execute user-defined functions dynamically in a Node.js application without having to restart the server

I am exploring the potential for allowing users to insert their own code into a Node application that is running an express server. Here's the scenario: A user clicks 'save' on a form and wants to perform custom business validations. This ...

Exporting key/value objects with React components as values in Typescript

I have a .tsx file where I need to export an object containing key/value pairs. Each value is going to be a React component used in another file. While I will have multiple key/value pairs, I'm focusing on just one at the moment. object.tsx import { ...