Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

254
Vistas
Connect the authentication service with the AuthGuard (simple issue)

I guess it's quite simple issue, but unfortunately I don't really know how to deal with it.

I'm trying to connect my UserAuthenticationService service with the ActivationGuard.

UserAuthenticationService.ts:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

@Injectable()
export class UserAuthenticationService {
    isUserAuthenticated: boolean = false;
    username: string;

    constructor(private http: Http) {
    }

    authentication() {
        this.http.get(`http://localhost/api/auth/isLogged/${this.username}`)
            .subscribe(res => { //^^returns true or false, depending if the user is logged or not
                    this.isUserAuthenticated = res.json();
                },   
                err => {
                    console.error('An error occured.' + err);
                });
    }


}

ActivationGuard.ts

import {Injectable} from '@angular/core';
import {Router, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {UserAuthenticationService} from './UserAuthenticationService';

interface CanActivate {
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|Promise<boolean>|boolean
}

@Injectable()
export class WorksheetAccessGuard implements CanActivate {

    constructor(private router: Router, private userService: UserAuthenticationService) {
    }

    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

        if (this.userService) {
            this.router.navigate(['/']);
            return false;
        }
        return true;
    }
}

Note

It works great, if I just use localStorage to store the information if the user is logged or not:

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    if (!localStorage.getItem('currentUser')) {
        this.router.navigate(['/']);
        return false;
    }
    return true;
}

But how can I connect the service with the guard? Looking forward for any kind of help. Thank you in advance.

If you need any more information, please let me know and I will edit my post.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Call authentication() method of UserAuthenticationService either in constructor or On ngOnit then it sets the isUserAuthenticated variable and use that in the ActivationGuard.ts

UserAuthenticationService.ts:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

@Injectable()
export class UserAuthenticationService {
    isUserAuthenticated: boolean = false;
    username: string;

    constructor(private http: Http) {
    this.authentication();
    }

    authentication() {
        this.http.get(`http://localhost/api/auth/isLogged/${this.username}`)
            .subscribe(res => { //^^returns true or false, depending if the user is logged or not
                    this.isUserAuthenticated = res.json();
                },   
                err => {
                    console.error('An error occured.' + err);
                });
    }


}  

ActivationGuard.ts

 @Injectable()
export class WorksheetAccessGuard implements CanActivate {

    constructor(private router: Router, private userService: UserAuthenticationService) {
    }

    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

        if (this.userService.isUserAuthenticated) {
            this.router.navigate(['/']);
            return false;
        }
        return true;
    }
}
over 4 years ago · Santiago Trujillo Denunciar

0

This is not the right approach for doing it. Every time you call the service , it initialize a new instance and hence you get a false.

You should create a singleton service instance ( via the main module in your app) - where it will contain your app state ( in memory / localstorage)

Then , when you'll call UserAuthenticationService - you won't update its owbn parameter but the main's one ( the singleton).

I suggest you to use a BehaviourSubject ( read about it , it's like a Subject but it also yields its last value without waiting to emit a value manually).

From that point your app can see from anywhere ig the user is logged in or not.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda