Home > Software engineering >  I want to navigate to Another page after I click Login
I want to navigate to Another page after I click Login

Time:12-18

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
},

CodePudding user response:

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.

CodePudding user response:

Do that in the ngOnInit in app component :

ngOnInit(){
  if (localStorage.getItem('authToken') != null){
    this.router.navigete(['login'])
   }
}

or in the login function do that :

login(user: User) {
 this.authService.login(user).subscribe((token: string) => {
    if(token !=null)  {
       localStorage.setItem('authToken', token); 
       this.router.navigate(['otherPath'])
     }
  });
}
  • Related