Filipe Tabosa
Filipe Tabosa

Reputation: 303

CanActivate with Modal/selector

I am currently working on the authentication service of an application. This service works with a token generated by the back-end. As it is now, if the token is expired it will redirect the user to the login page; However, I would like to implement a solution where it does not redirect the user, but instead call a login modal where the user would put its information. Here is a snippet of the current code.

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthenticationService } from './authentication.service';

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private router: Router, private authenticationService: AuthenticationService) {
    }

    canActivate() {
        try {
            if (this.authenticationService.loggedIn()) {
                return true;
            }
        } catch (error) {
            console.log(error);
        }
        this.router.navigate(['/login']);
        return false;
    }
}

I have another component with the login modal.

@Component({
    selector: 'login-modal',
    templateUrl: './login-modal.component.html',
    styles: []
 })

Basically what I want to do is change the usage of this.router.navigate(['/login']) to the LoginModalComponent, with selector: 'login-modal'. How can I change the CanActivate method in order to call the LoginModalComponent?

I saw a solution for this problem that uses Bootstrap 4; however, my application uses Bootstrap 3, so I cannot implement it.

Upvotes: 1

Views: 1016

Answers (1)

rjustin
rjustin

Reputation: 1439

You have a few options but here are a few suggestions:

  • navigate to another page expection to open the login and hang on to the page you are navigating from.
  • Have a modal service that takes in the the login component and returns a promise or observable to the route guard.
  • have the login modal at an application level and a service to open it from the route guard.

I think you should aim to essentially provide a promise to the guard that when resolved will know if the user logged back in or not.

Hope this helps

Upvotes: 1

Related Questions