I've been grappling with understanding Angular Observables, but I've managed to get it working. My goal is to fetch data for my dynamic navigation bar. I successfully verified whether the user is logged in or not and displayed the Login or Logout button accordingly. However, I'm facing difficulty in retrieving user data. Here's my approach:
This is my User Interface:
interface User{
status:boolean,
username:string,
email:string
}
User service:
export class UserService {
private Userr :BehaviorSubject<User>
constructor(private http:HttpClient) {
this.Userr = new BehaviorSubject<User>({
status:false,
username:"",
email:""
});
}
setUser(user:User){
this.Userr.next(user);
}
get getUserData{
return this.Userr.asObservable();
}
get retrieveData{
return this.http.get<User>('/api/userdata')
}
}
Below is my navbar ts component implementation:
export class NavbarComponent implements OnInit {
isLoggedIn$: Observable<boolean>;
User$ : Observable<User>;
constructor(private authService: AuthService,private router:Router,private
user:UserService) { }
ngOnInit() {
this.isLoggedIn$ = this.authService.getLoggedIn;
this.User$ = this.user.getUserData;
}
}
I chose not to include the logout function as I wanted to focus solely on fetching data. In the navbar html component, I have the following:
<a class="nav-link" (click)="logout()" routerLink='/welcome'>Welcome
{{(User$ | async).username}}!, Log Out!</a>
However, the error I'm encountering is that User$.username is undefined. Thank you.
Edit For those facing a similar issue, here's how you can retrieve the username:
{{(User$ | async).username}}!