I do the call to api in ngOnInit() and I want to do some more things on data from api in ngOnInit().
But when I try to console.log() my data I got undefined and can not process more. When I console.log() the same data in getUsers() method when I subscribe data from service I have my array with json data. Api response:
{"items":[{"id":"1","name":"Adam","age":20},{"id":"2","name":"Cris","age":32}]}
UserResults is my whole JSON. And I need only users in my users Array not item.
service.ts
public getUsers(): Observable<UserResults> {
return this.httpClient.get<UserResults>(baseURL);
}
component.ts
export class SidebarComponent implements OnInit {
usersResult: UserResults;
users: Users[];
constructor(private dataService: DataService) { }
ngOnInit(): void {
this.getUsers();
// shouldn't be users array available ???
console.log(this.getUsers()) // undefined
///more calculations
}
private getUsers() {
this.dataService.getUsers().subscribe(
data => {
this.users = data.items;
console.log(this.getUsers()) // correct data in json array
}
)
}
}
How should I handle it the best way?