I'm trying to get the username from the login view/component after he logs in and add it to the navbar(and keep it unless he logs out).
I think i require to use services/observables but i'm new with angular and i don't have a clue where/how to start.
Any help will be thankful.
Thanks!
Right now i'm using Authguard and a User Service.
This is my code:
Authguard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import {UserService} from './user.service';
@Injectable()
export class AuthguardGuard implements CanActivate {
constructor(private user: UserService) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.user.getUserLoggedIn();
}
}
User-Service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class UserService {
public isUserLoggedIn;
public matricula;
constructor() {
this.isUserLoggedIn = false;
}
setUserLoggedIn() {
this.isUserLoggedIn = true;
}
getUserLoggedIn() {
return this.isUserLoggedIn;
}
setUserLoggedOut() {
this.isUserLoggedIn = false;
}
}
Login.ts
import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Router} from '@angular/router';
import swal from 'sweetalert2';
import {UserService} from '../user.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
datos: any;
matricula: any;
contrasena: any;
constructor(private http: HttpClient, private router: Router, private user: UserService) {
}
ngOnInit() {
if (this.user.getUserLoggedIn() === true) {
this.router.navigate(['/productos']);
} else {
}
}
getCredentials() {
this.http.get('http://localhost/cafeteria/login/validar.php').subscribe((data: any) => {
this.datos = data;
this.validar();
});
}
validar() {
if (this.datos[0].matricula === this.matricula) {
if (this.datos[0].contrasena === this.contrasena) {
this.user.setUserLoggedIn();
this.router.navigate(['/productos']);
switch (this.datos[0].idrol) {
case '1':
this.router.navigate(['/productos']);
break;
case '2':
this.router.navigate(['/cPanel']);
break;
case '3':
this.router.navigate(['/cPanel']);
break;
}
}
} else {
swal('Datos Incorrectos');
}
}
}