Angular 5 - Add logged username into the navbar

2019-09-28 05:54发布

问题:

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');
    }
  }
}

回答1:

You need to store the logged in user in some service after a successful login. Most preferably your AuthService, or UserService. Then just inject that service to your navbar component and use interpolation to display that user's username.

I would do something like this:

user.service.ts

private _loggedInUser?: User;

get loggedInUser(): User {
    return this._loggedInUser;
}
set loggedInUser(user: User) {
    this._loggedInUser = user;
}

I'd recommend using localStorage or sessionStorage instead of storing loggedInUser in memory.

login.component.ts

login() {
    // ... validate
    if (valid) {
        this.user.loggedInUser = user;
        this.router.navigate(/* your path here */);
    }
}

navbar.component.ts

constructor(public user: UserService) { }

navbar.component.html

<h1>Hello, {{user.loggedInUser}}</h1>


标签: angular