After spending some time on this issue, I am still puzzled as to why I am consistently receiving an empty observable.
Service:
import { Injectable } from '@angular/core';
import { WebApiService } from './web-api-service';
import { BehaviorSubject, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private currentUserName: Subject<any> = new BehaviorSubject<any>({});
private currentUser: Subject<any> = new BehaviorSubject<any>({});
constructor(private webApi: WebApiService) { }
setCurrentUsername(username) {
this.currentUserName.next(username);
}
setCurrentUser(user) {
this.webApi.GetMenuItems(JSON.stringify(user)).subscribe(response => {
if (response !== []) {
let res = response.d.replace(/\n|\r/g, ""); //eliminate new line and return characters
res = JSON.stringify(eval("(" + res + ")")); //convert string to valid json
res = JSON.parse(res); //convert to javascript object
this.currentUser.next(res); //store object
}
});
}
get username() {
return this.currentUserName.asObservable();
}
get user() {
return this.currentUser.asObservable();
}
}
Home Component:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ColorGeneratorService } from '../../services/color-generator.service';
import { AuthService } from '../../services/auth.service';
import { Subscription } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.scss']
})
export class HomePageComponent implements OnInit, OnDestroy {
user: Subscription;
username: string ;
roleArray: Array<any>
constructor(private auth: AuthService, private route: ActivatedRoute) { }
ngOnInit() {
this.username = this.route.snapshot.paramMap.get('username');
this.auth.setCurrentUsername(this.username);
this.auth.setCurrentUser({ username: this.username });
this.user = this.auth.user.subscribe(user => {
this.roleArray = user.roles;
});
}
}
Secondary Component:
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-subject-page',
templateUrl: './subject-page.component.html',
styleUrls: ['./subject-page.component.scss']
})
export class SubjectPageComponent implements OnInit {
user: Subscription;
username: string;
constructor(private auth: AuthService) { }
ngOnInit() {
this.user = this.auth.user.subscribe(user => {
console.log(user);
});
}
}
Upon further investigation, the Home Component successfully "sets" the user in the auth service, with a button that navigates to the subject-page component. However, upon clicking the button and transitioning to the subject-page component, the console.log only shows an empty object {} implying that the user information was not retained. You can view a Stackblitz example of the issue here.