After login, until the user logs out , the login page route should not be accessed. how to implement it in Angular. Please give a detailed explanation with necessary code.

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs/Observable';
import {AngularFireAuth } from 'angularfire2/auth';

import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
@Injectable()
export class AuthRedirectService {
  //service which helps to redirect to profile page from login/sigup page if an user is already logged in.
  constructor(private auth: AuthService, private router: Router,
              private angularfireauth: AngularFireAuth) { }
  canActivate(next: ActivatedRouteSnapshot,
              state: RouterStateSnapshot): Observable<boolean> | 
                                           Promise<boolean> | boolean  {
    //this.router.navigate(['/profile']);
    if (this.auth.isUserLoggedIn()==false) {
      console.log("login status from guard: ",this.auth.isUserLoggedIn);
      return true;
    }
    return false; 
  }
}
1

There are 1 best solutions below

0
On
Include the following code in authguard.ts:

import { Injectable, Component } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class AuthGuard  {
    [x: string]: any;

    constructor(private router: Router) { 

    }

    canActivate(routeerstate?: any) {
      if (!this.auth.isUserLoggedIn()) {
        this.router.navigate(['login']);  // not authenticated so always redirect to login
      } else if(routeerstate._routerState.url === '/login'){
        this.router.navigate(this.router.url]); // authenticated so stay in the current url
      }
    }
}

routeerstate._routerState.url gets you unactivated URL(to URL) i.e the url the user is trying to enter, this.router.url gets you the current URL (from URL), rest you can get it from comments in above code

export const routes: Routes = [
  { path: 'login', component: LoginComponent, pathMatch: 'full',canActivate: [AuthGuard] },
  { path: 'authenticatedpage1', component: authenticatedPageComponent, pathMatch: 'full',canActivate: [AuthGuard] }
];