Search code examples
angularangular-ui-routerangular2-routing

I want to navigate to Another page after I click Login


I use .Net as back-end and now im working with angular for routing part i'm stuck in navagite to another page using authentication I supposed to use navigate router after subscribe but I don't know how

export class LoginComponent {

  title = 'webUI.UI';
  user = new User();

  constructor(private authService: AuthService, private router: Router) {}

  
  login(user: User) {
    this.authService.login(user).subscribe((token: string) => {
      localStorage.setItem('authToken', token);
    });

    if (localStorage.getItem('authToken') != null){
??????
      
    }
  }
}

my router

const routes: Routes = [

  {
    path: 'login',
    component: LoginComponent
},


{

  path: 'signup',
    component: SignupComponent
},

{
  path: 'home',
  component: EmployeepListComponent
},

Solution

  • You can use a Guard, too for this. Read more here. The canActivateguard can protect any component inside your router. So you can check your token or anything and then redirect to login, or the page the user want to navigate.

    import { Injectable } from "@angular/core";
    import { Router } from "@angular/router";
    import {
      CanActivate,
      ActivatedRouteSnapshot,
      RouterStateSnapshot
    } from "@angular/router";
    import { Observable } from "rxjs";
    import { tap } from "rxjs/operators";
    
    import { AuthService } from "./auth.service";
    
    @Injectable()
    export class CanActivateGuard implements CanActivate {
    
      constructor(
        private auth: AuthService,
        private router: Router
      ) {}
    
      canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
      ): Observable<boolean> | Promise<boolean> | boolean {
        const token = this.auth.getToken();
        const url = "/token/verify/";
    
        if (!token) {
          this.router.navigate(["/login"]);
          return false;
        }
    
        return this.auth.verifyToken().pipe(
          tap(allowed => {
            if (!allowed) this.router.navigate(["/login"]);
          })
        );
      }
    }
    
    

    Here is a Stackblitz example.