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; } } 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.
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; } }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.