Search code examples
angularmeteorauthenticationangular-meteorangular2-meteor

Login Logic With Angular 2 Meteor?


I want to achieve a typical login/register setup:

  • Prevent users from accessing /app and all children of /app if they are not logged in
  • Prevent users from accessing /login and /register if they are logged in

Now, I'm using a setup that looks something like this:

@Injectable()
export class LoggedInGuard implements CanActivate, CanActivateChild {
    canActivate(...): boolean {
        if (Meteor.userId() != null) {
            return true;
        }
        this.router.navigate(['/login']);
        return false;
    }
    canActivateChild(...): boolean {
        return this.canActivate(childRoute, state);
    }
}

And I put in my routes, I put {path: 'app', component: TasksListComponent, canActivate: [LoggedInGuard]}. However, this does not prevent the user from accessing login/register pages if they are logged in. I was wondering if there's a better way to do this, without creating another separate Injectable.

**Note - I'm not using Iron Router, I'm using @angular/router


Solution

  • you can redirect user to some other component if they are login. just put this first in ngOnInit().

     ngOnInit() {
     //*** checking if user is already login if login redirect to someother page based on your custom condition
            if (Meteor.userId()) {
                this._router.navigate(['otherpage']);
            }
    
        }