Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
Conecte el servicio de autenticación con AuthGuard (problema simple)

Supongo que es un problema bastante simple, pero desafortunadamente no sé cómo lidiar con eso.

Estoy tratando de conectar mi servicio UserAuthenticationService con 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; } }

Nota

Funciona muy bien, si solo uso localStorage para almacenar la información si el usuario está conectado o no:

 public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { if (!localStorage.getItem('currentUser')) { this.router.navigate(['/']); return false; } return true; }

Pero, ¿cómo puedo conectar el servicio con el guardia? Esperando cualquier tipo de ayuda. Gracias de antemano.

Si necesita más información, hágamelo saber y editaré mi publicación.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Llame al método de autenticación () de UserAuthenticationService ya sea en el constructor o en ngOnit, luego establece la variable isUserAuthenticated y la usa en ActivationGuard.ts

Servicio de autenticación de usuario.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 Report

0

Este no es el enfoque correcto para hacerlo. Cada vez que llama al servicio, inicializa una nueva instancia y, por lo tanto, obtiene un falso.

Debe crear una instancia de servicio singleton (a través del módulo principal en su aplicación), donde contendrá el estado de su aplicación (en memoria/almacenamiento local)

Luego, cuando llame a UserAuthenticationService , no actualizará su propio parámetro sino el principal (el singleton).

Le sugiero que use un BehaviourSubject (lea sobre esto, es como un Sujeto pero también arroja su último valor sin esperar a emitir un valor manualmente).

Desde ese punto, su aplicación puede ver desde cualquier lugar si el usuario está conectado o no.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!