I'm trying to fetch a list of users from a backend API. It all works perfectly unless that once I log the getAllUsers()
method in the ngOnInit
I get the data, but when I log the variable containing the list of users I get undefined.
Here is my code:
users:User[];
constructor(private userService:UserService) { }
ngOnInit(): void {
this.getAllUsers();
console.log(this.users); // ==> shows undefined
}
getAllUsers() {
this.userService.getAll().subscribe({
next:(data) => {
console.log(data); // ==> shows the result
this.users=data
}
})
}
Can anyone explain the difference between them? And how can I access the response outside the subscribe method? I'm still new to angular though! thanks in advance!