Hola soy nuevo en angular y llevo ya dias tratando de solucionar este problema y la verdad no se que hacer.
Hace días vengo tratando de hacer un login en Angular que al iniciar sesión muestre en el navbar el nombre de la persona que inicio sesión y su rol, lo que he hecho es guardar pues el token en el localStorage, al igual que el nombre y el rol, entonces lo que hacia era que al iniciar el componente login, este seteaba el nombre y el rol y luego en appcomponent obtenía esos datos del localStorage y los ponia en el navbar, todo salia mal, al iniciar sesión se llenaba de errores al decir que no podía acceder a la propiedad del nombre de usuario y el rol, ya que estaba todo indefinido, al dar F5 me cargaba todo normal y me salia el usuario y el rol, busque soluciones y me recomendaron usar subject y eso es lo que hice, al usar subject por lo menos al iniciar sesión ya no me daba error, me cargaba correctamente todo, pero si recargaba la página, volvía a salir los errores, todo volvía a quedar indefinido, este es mi código :
APPCOMPONENT:
import { Component } from "@angular/core";
import { AuthService } from "./services/auth.service";
import { Subject } from 'rxjs/Subject';
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
public static updateUserStatus: Subject<boolean> = new Subject();
user: any;
constructor(private authService: AuthService) {
AppComponent.updateUserStatus.subscribe(res => {
this.user = this.authService.getUser();
})
}
ngOnInit() {
}
}
SIGN IN COMPONENT
import { Component, OnInit } from "@angular/core";
import { AuthService } from "../../services/auth.service";
import { Router } from "@angular/router";
import Swal from "sweetalert2";
import { AppComponent } from "src/app/app.component";
@Component({
selector: "app-signin",
templateUrl: "./signin.component.html",
styleUrls: ["./signin.component.css"],
})
export class SigninComponent implements OnInit {
user = {};
constructor(private authService: AuthService, private router: Router) {}
ngOnInit() {}
signIn() {
this.authService.signIn(this.user).subscribe(
(res) => {
this.authService.setUser(res.datos);
this.authService.setToken(res.token);
//localStorage.setItem("token", res.token);
AppComponent.updateUserStatus.next(true);
this.router.navigate(["/home"]);
//localStorage.setItem("datos", JSON.stringify(datosUser));
Swal.fire(
"Bienvenido " + res.datos.nombre_usuario,
"Tu Rol es: " + res.datos.rol,
"success"
);
},
(err) => {
Swal.fire({
icon: "error",
title: "Error",
text:
"No se ha podido iniciar sesion, verifique su correo y contraseña",
});
}
);
}
}
AUTHSERVICE:
import { Injectable } from "@angular/core";
import { HttpClient, HttpInterceptor } from "@angular/common/http";
import { Router } from "@angular/router";
import { isNullOrUndefined } from "util";
import { Observable } from "rxjs/internal/Observable";
import { map } from "rxjs/operators";
@Injectable({
providedIn: "root",
})
export class AuthService {
private URL = "http://localhost:3000";
constructor(private http: HttpClient, private router: Router) {}
signUp(user) {
return this.http
.post<any>(this.URL + "/signup", user)
.pipe(map((res) => res));
}
signIn(user): Observable<any> {
return this.http
.post<any>(this.URL + "/signin", user)
.pipe(map((res) => res));
}
loggedIn() {
if (localStorage.getItem("token")) {
return true;
}
}
getToken() {
return localStorage.getItem("token");
}
getUser(){
return JSON.parse(localStorage.getItem("datos"));
}
logOut() {
localStorage.removeItem("token");
localStorage.removeItem("datos");
this.router.navigate(["/home"]);
}
setToken(token) {
localStorage.setItem("token", token);
}
setUser(user) {
localStorage.setItem("datos", JSON.stringify(user));
}
}