Angular 5 Redirect if not logged in - CanActivate AuthGuard - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline
Angular 5 Redirect if not logged in - CanActivate AuthGuard

Angular 5 Redirect if not logged in - CanActivate AuthGuard

In this article, I will learn how to redirect one page to other page and also discuss how to use the AuthGuard and CanActivate in Angular 5 applications.

Three options are available to redirect page in Angular 5 –
1.      Imperatively redirect the user in AppComponent
2.      Use the route data property
3.      Use a CanActivate guard

The AuthGuard should call an application service that can login a user and retain information about the current user.

Options 1 – Imperatively redirect the user in AppComponent
@Component({
  selector: 'app-root',
  template: `.....`
})
export class AppComponent {
  constructor(private _authServiceAuthService_routerRouter) {
    if (_authService.isLoggedIn()) {
      _router.navigate(['user']);
    }
  }
}
This is not good practice and I will not recommend using this options.

Options 2 - Use the route data property
This is the best solution and used by many expert programmers. You can simply add some metadata in the routes declaration to indicate that - “this route requires that the user must be loggedIn”.

const APPROUTESRoutes = [
    {path: 'dashboard'component: AppComponentdata:{requiresLogin: true}},
    {path: 'user'component: UserComponentdata:{requiresLogin: true}}
];
This is the best approach to redirect if not logged in and I will recommend to this option.

Options 3 -Use a CanActivate guard
Firstly add a CanActivate guard to all the routes that require the user to be logged in and my guard is called AuthGuardand see the following example –

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    UserComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    RouterModule.forRoot([
      path: ''component: AppComponentpathMatch: 'full'canActivate: [AuthGuard]},
      path: 'user'component: UserComponentcanActivate: [AuthGuard]},
      path: 'login'component: LoginComponent}])
  ],
  providers: [EmployeeServiceValidationService,
          AuthenticationServiceUserService],
  bootstrap: [AppComponent]
})
export class AppModule { }


And
import { Injectable } from '@angular/core';
import { CanActivateActivatedRouteSnapshotRouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import {Routerfrom '@angular/router';
import { AuthServiceService } from './auth-service.service';

@Injectable()
export class AuthGuard implements CanActivate {

  //constructor initialization
  constructor(private authServiceAuthServiceService,   private routeRouter){  }

  //can Activate Route
  canActivate(
    nextActivatedRouteSnapshot,
    stateRouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      if(this.authService.isLoggednIn()){
        this.route.navigate(["user"]);
        return true;
      }else{
        return false;
      }
  }
}

This is also best approach to redirect if not logged in and this one is also recommend to this option.

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.