Protecting Angular Routes with AuthGuard

Currently, I am facing an issue with my persistent login functionality. Everything seems to be working fine except when I reload the page from a protected dashboard that requires AuthGuard. Upon reloading, I get redirected to the login page even though I am still logged in and the navbar functions properly. Any suggestions or solutions would be greatly appreciated.

export class AuthGuard implements CanActivate {

    constructor(private auth: AuthService, private router: Router) {

    }

    canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        return this.auth.getLoggedIn
            .pipe(
                map((res: boolean) => {
                    console.log(res);  // It returns false when I reload the page    
                    if (!res) {
                        this.router.navigate(['login']);
                        return false;
                    }
                    return true;
                })
            );
    }
}

Below is my authentication service code:

export class AuthService {

    private loggedIn: BehaviorSubject<boolean>;

    constructor(private http: HttpClient) {

        this.loggedIn = new BehaviorSubject<boolean>(false);
    }

    setLoggedIn(value: boolean) {
        this.loggedIn.next(value);
    }

    get getLoggedIn() {
        this.updatelogin().subscribe(res => {
            this.loggedIn.next(res);

        })
        return this.loggedIn.asObservable();
    }

    updatelogin() {
        return this.http.get<boolean>('/api/islogged'); // An API call to check if user is authenticated
    }
}

I have removed some unnecessary code for clarity, but feel free to ask if you need more information.

Answer №1

Solving the problem is as simple as using a Subject instead of a BehaviorSubject:

First, create a Subject with an initial value of false.

this.loggedIn = new Subject<boolean>(false);

Next, trigger an HTTP call to update the login status.

this.updateLogin().subscribe(res =>{
   this.loggedIn.next(res);
 })

Make sure to wait for the HTTP call to complete before returning the value.

return this.loggedIn.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

Updating the Bootstrap entry dynamically within the @NgModule module

My web application has a specific requirement where it can only be accessed through example.com/index.html without any parameters. The backstory behind this restriction is quite lengthy, so let's not delve into that. Within the index.html file, I have ...

Font loading error in Angular 2 - Denied access to load font

Recently, I started experimenting with Angular 2 and delved into working with routes. Surprisingly, everything was functioning seamlessly until I introduced routes into the mix. Now, whenever I navigate to /home, an error pops up. Refused to load the font ...

Formulate a multi-line string using a collection in React's JavaScript framework

I'm working on a React function that involves a set and I need to update an HTML element using the data from this set. Below is an example of my code: const updateElement = (mySet) => { document.getElementById('myId').innerHTML = Arra ...

Is there a way to preserve the original index signature of an object while also defining the type of its values?

I have a large object containing various animals with different characteristics. I'm looking to properly type this object in TypeScript. interface Animal { legs: 0 | 1 | 2 | 3 | 4; } const Animals: Record<string, Animal> = { snake: { le ...

Why do I keep being told that the property doesn't exist?

I have the following code in one file: function test<T extends {}>(arg:T):any { return arg.name } In another file, I have this code: interface IItem { name: string } console.log(test<IItem>({name:'3'})) When I try to access ...

Is there a way to access a specific argument in yargs using typescript?

The idea behind using yargs is quite appealing. const argv = yargs.options({ env: { alias: 'e', choices: ['dev', 'prod'] as const, demandOption: true, description: 'app environment&apos ...

Issue with TypeScript when using destructuring on an object

When attempting to destructure data from an object, I encountered the error message Property XXXX does not exist on type unknown. This issue arose while using React Router to retrieve data. let {decoded, reasonTypes, submissionDetails} = useRouteLoaderDa ...

setting up angular 4 application on an IIS server

When running ng build --prod --base-href=/my folder/subfolder/, I also made sure to copy the dist folder into the specified subfolder. After setting the physical path in IIS, I tried to browse the site but only encountered a blank screen with no error mes ...

Verify that the password is entered correctly in Angular2

My Angular2 form looks like this: this.registerForm = formBuilder.group({ 'name': ['', Validators.required], 'email': ['', Validators.compose([Validators.pattern("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+&bso ...

When trying to style a Material UI component in Mui v5, no matches for overloads were found

In my attempt to enhance the style of a Material UI Component (TextField) shown in the image, I encountered an error that seems to persist no matter what troubleshooting steps I take. Interestingly enough, I never faced such issues when working with styled ...

Retrieve the value of a local variable in the ngOnInit function from a different function

Recently, I've started working with Angular and TypeScript. I am facing an issue where I need to access a local variable that is declared in the ngOnInit function from outside it, but I'm not quite sure how to achieve this correctly. This variabl ...

TypeScript and Angular: Harnessing the Power of Directive Dependency Injection

There are multiple approaches to creating Angular directives in TypeScript. One elegant method involves using a static factory function: module app { export class myDirective implements ng.IDirective { restrict: string = "E"; replace: ...

Issue with angular2-query-builder where the drop-down value does not reset or update

Currently, I am facing an issue with updating the dropdown value after changing its corresponding field. It seems to retain the initial data or show outdated information when custom components, such as the "select" tag, are used to mimic a dropdown functio ...

When using Observables in AngularFire2, the $ref property does not get captured

Recently, I started working with AngularFire2 (version 4.0.0-rc.1) and encountered a challenge that has me stuck: getWishlist$(): FirebaseListObservable<{}> { return <FirebaseListObservable<{}>>this.store.select(getFirebaseUID) ...

Can you use setValidators() in Angular to validate two patterns simultaneously?

Is there a way to validate both IP address and IP address range in a single control using Angular? I have tried using the following code snippet: controls["CapPoolVolExpolAldClientControl"].setValidators([Validators.required, Validators.pattern(/([0-9]){1 ...

Encountering the ExpressionChangedAfterItHasBeenCheckedError message despite updating the property via the @Output event

Attempting to update a property on the parent component through an event in the child component has proved challenging. Research suggests that this can be achieved using @Output as it is the recommended method to transmit data from child component to pare ...

Ways to limit file access and downloads on an IIS server

After deploying our Angular app (dist folder) on an IIS server, everything seems to be working well. However, there is a concerning issue where anyone can access and download the font files directly from the server without needing to log in. For example, o ...

Stop users from navigating back to specific routes by implementing route guards in Angular

I'm pondering whether it's possible to restrict users from revisiting certain routes Here's my dilemma: after a user logs in and follows the login/callback route for authentication, they can get stuck if they navigate back to that same rout ...

What external libraries does Angular 4 utilize during execution, aside from RxJS?

Angular 4 relies on RxJS types in its public API and also internally depends on RxJS. It would be beneficial to explore if Angular utilizes other external packages for certain functionalities, allowing us to incorporate them into our own projects. This ap ...

Attaching and detaching dynamic views in Angular within an ngFor loop

I'm currently dealing with an issue where I have a list of chat items that are loaded dynamically. When a user clicks on a specific item, I need to open/close a static component/section (such as a reactions menu) right below that particular chat item. ...