I am working with angular and my ngOnInit subscribes to data and sets it to my username property. What I do not understand is when I console.log(this.username) I will get undefined depending on what line of code I position the console log and I do not understand why it is doing this.
export class DashboardComponent implements OnInit {
username: string;
ngOnInit() {
this.authService.getProfile().subscribe(profile => {
this.username = profile.user.username;
console.log(this.username); <============== works here
},
err => {
console.log(err);
return false;
});
this.getLists();
console.log(this.username); <=========== get undefined here
}
getLists(): void {
console.log(this.username); <=========== get undefined here (need it to work here)
}
addList(newItem): void {
console.log(this.username); <=========== works here
}
My addList function is linked to an (onClick) event and the console log works here and when it is directly inside my subscribe function. But when when I tried to console log it inside my getList function or on the last line of my ngOnInit I get undefined and I do not understand why it is doing this? What am I missing?