My goal is to display the name of the currently logged-in user in the header of my application. However, I encountered an issue where upon refreshing the page, the value would be lost due to SPA behavior (even though the data is stored in local storage). To address this, I created a function within my authentication service that retrieves the logged-in user from local storage and stores it for use. This function is called within the ngOnInit() of the header component. Despite subscribing to the values, I am encountering undefined results. The logic seems correct as I am re-assigning the values before retrieving them from the service.
Authentication Service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { CurrentUserInterface } from '../interfaces/current-user.interface';
@Injectable()
export class AuthenticationService {
private rootUrl = 'testapi.com';
private currentUser = new BehaviorSubject<CurrentUserInterface>();
private isAuthorized: BehaviorSubject<boolean> = new BehaviorSubject(false);
constructor(private http: HttpClient) { }
setCurrentUser(): void {
if(localStorage.getItem("currentUser")) {
this.currentUser.next(JSON.parse(localStorage.getItem("currentUser")));
this.isAuthorized.next(true);
}
else {
this.isAuthorized.next(false);
}
console.log(this.currentUser.value); **//HAS VALUES**
}
getCurrentUser(): Observable<CurrentUserInterface> {
return this.currentUser.asObservable();
}
checkAuth(): Observable<boolean> {
return this.isAuthorized.asObservable();
}
}
Header Component
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthenticationService } from '../_shared/services/authentication.service';
import { CurrentUserInterface } from '../_shared/interfaces/current-user.interface';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
private currentUser = new Observable<CurrentUserInterface>;
private isAuthorized: Observable<boolean> = false;
constructor(private router: Router,
private authenticationService: AuthenticationService) { }
ngOnInit() {
this.authenticationService.setCurrentUser();
this.isAuthorized = this.authenticationService.checkAuth()
.subscribe(
isAuthorized => {
this.isAuthorized = isAuthorized;
},
error => {
console.log(error);
}
);
this.currentUser = this.authenticationService.getCurrentUser()
.subscribe(
currentUser => {
this.currentUser = currentUser;
},
error => {
console.log(error);
}
);
console.log(this.currentUser.value); **// UNDEFINED**
console.log(this.isAuthorized.value); **// UNDEFINED**
}
logout() {
this.authenticationService.logout();
this.router.navigate(['../login'], { relativeTo: this.route });
}
}