Redirect before logging into the system - Angular

Asked

Viewed 471 times

1

I have a login screen, with the total "/Authentication/login".

How to do at the angle when the user enters the system, it goes straight to this route ?

After logging in if it enters this route, it always validates and if the user has logged in it goes to the route "/" ?

Route

import { Routes } from '@angular/router';

import { FullComponent } from './layouts/full/full.component';
import { AppBlankComponent } from './layouts/blank/blank.component';

export const AppRoutes: Routes = 
[
  {
    path: '',
    component: FullComponent,
    children: 
    [
      {
        path: '',
        loadChildren: './dashboards/dashboards.module#DashboardsModule'  
        /*pathMatch: 'full',
        redirectTo: '/dashboards/dashboard1', */
      },
      {
        path: 'configuracao',
        loadChildren: './paginas/configuracao/configuracao.module#ConfiguracaoModule'  
      },
      {
        path: 'arquivo',
        loadChildren: './paginas/arquivo/arquivo.module#ArquivoModule'  
      },
      {
        path: 'declaracao',
        loadChildren: './paginas/declaracao/declaracao.module#DeclaracaoModule'  
      },
      {
        path: 'parametro',
        loadChildren: './paginas/parametro/parametro.module#ParametroModule'  
      },
      {
        path: 'endereco',
        loadChildren: './paginas/endereco/endereco.module#EnderecoModule'  
      },
      {
        path: 'contribuinte',
        loadChildren: './paginas/banco/banco.module#BancoModule'  
      },
      {
        path: 'dashboard',
        loadChildren: './dashboards/dashboards.module#DashboardsModule'  
      }
    ]
  },
  {
    path: '',
    component: AppBlankComponent,
    children: 
    [
      {
        path: 'authentication',
        loadChildren: './authentication/authentication.module#AuthenticationModule'
      }
    ]
  },
  {
    path: '**',
    redirectTo: '404' 
  }
];

Angular version: 5.0.0

  • which version of angular? Can your route code?

  • Included in the main question

  • When defining path: '' this means it will be your default route. Why not add your component to the default route?

  • So I was handed the project this way. What would be the difference ? In this project I’m working on, there are routes and subroutes. Each subroute is called in its module.

2 answers

0

I did it once, I did it this way using redirectTo and pathMatch -

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { EventosComponent } from './pages/eventos/eventos/eventos.component';
import { EventosCadastroComponent } from './pages/eventos/eventos-cadastro/eventos- 
cadastro.component';
import { AuthComponent } from './pages/auth/auth.component';
import { AuthGuard } from './shared/utils/auth.guard';


const routes: Routes = [
   { path: '', redirectTo: '/auth', pathMatch: 'full' },
   { path: 'auth', component: AuthComponent }
];

0

I did so and so it resolved.

Canactivateauthguard

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthenticationService } from '../servico/authentication/authentication.service';

@Injectable()
export class CanActivateAuthGuard implements CanActivate {

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

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.authService.isLoggedIn()) {
      return true;
    }
    this.router.navigate(['/authentication/login']);
    return false;
  }
}

Safe routes

import { Routes } from '@angular/router';
import { ArquivoComponent } from './arquivo/arquivo.component';
import { ArquivoFormComponent } from './arquivo-form/arquivo-form.component';
import { CanActivateAuthGuard } from '../../authentication/can-activate.authguard';

export const ArquivoRoutes: Routes = [
  {
    path: '',
    children: [
      {
        path: '',
        component: ArquivoComponent,
        canActivate: [CanActivateAuthGuard] 
      }
      , {
        path: 'novo',
        component: ArquivoFormComponent,
        canActivate: [CanActivateAuthGuard] 
      }
    ]
  }
];

Authenticationservice

import { Injectable } from '@angular/core'; import { Http, Headers, Response } from@angular/http; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/Operator/map'; import 'rxjs/add/Operator/catch'; import 'rxjs/add/observable/throw';

import { Usuario } from '../../modelo/usuario/usuario.model';
import { BASE_AUT_URL } from '../base-api-url-defaul';

@Injectable()
export class AuthenticationService {

    private base: string;
    private options: Function;

    private headers = new Headers({
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': 'true'
    });

    constructor(private http: Http) {
        this.base = BASE_AUT_URL
    }

    login(usuario: Usuario): Observable<boolean> {
        console.log(this.headers);
        return this.http.post(this.base, JSON.stringify({login: usuario.login, senha: usuario.senha}), {headers: this.headers})
            .map((response: Response) => {
                let token = response.json() && response.json().token;
                if (token) {
                    localStorage.setItem('currentUser', JSON.stringify({ username: usuario.login, token: token }));
                    localStorage.setItem('token', token);
                    localStorage.setItem('user', JSON.stringify(usuario.login));
                    localStorage.setItem('usuario', response.json().usuario);
                    localStorage.setItem('nomeUsuario', response.json().nomeUsuario);
                    localStorage.setItem('grupoUsuario', response.json().grupo);
                    return true;
                } else {
                    return false;
                }
            }
        ).catch(
            (error:any) => Observable.throw(error.json().error || 'Server error')
        );
    }

    getToken(): String {
        //var currentUser = JSON.parse(localStorage.getItem('currentUser'));
        //var token = currentUser && currentUser.token;
        var token = localStorage.getItem('token');
        return token ? token : "";
    }

    logout(): void {
        localStorage.removeItem('currentUser');
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        localStorage.removeItem('usuario');
        localStorage.removeItem('nomeUsuario');
        localStorage.removeItem('grupoUsuario');
    }

    isLoggedIn(): boolean {
        var token: String = this.getToken();
        return token && token.length > 0;
    }
}

I used as reference this article: Angular Authentication: Using Route Guards

Browser other questions tagged

You are not signed in. Login or sign up in order to post.