user.service.ts
import { BehaviorSubject } from 'rxjs';
import { TokenService } from './../token/token.service';
import { Injectable } from '@angular/core';
import { User } from './user';
import jwt_decode from 'jwt-decode';
@Injectable({
providedIn: 'root',
})
export class UserService {
private userSubject = new BehaviorSubject<User>(null!);
constructor(private tokenService: TokenService) {
this.tokenService.hasToken() && this.decodeAndNotify();
}
setToken(token: string) {
this.tokenService.setToken(token);
this.decodeAndNotify();
}
getUser() {
return this.userSubject.asObservable();
}
private decodeAndNotify() {
const token = this.tokenService.getToken();
const user = jwt_decode(token!) as User;
this.userSubject.next(user);
}
}
header.components.ts:
import { Observable } from 'rxjs';
import { UserService } from './../user/user.service';
import { Component } from '@angular/core';
import { User } from '../user/user';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
})
export class HeaderComponent {
user$: Observable<User>;
user!: User;
constructor(userService: UserService) {
this.user$ = userService.getUser();
this.user$.subscribe((user) => (this.user = user));
}
}
header.component.html:
<header class="fixed-top">
<nav class="navbar navbar-light bg-white">
<a class="navbar-brand">ALURAPIC</a>
<div>
<i class="fa fa-user-circle"></i>
<a class="ml-2"> {{ user.name }} </a>
</div>
</nav>
</header>