I've been looking for similar issues but couldn't understand what my problem is. I am a rookie with Angular.
I am calling the service.getUsers()
. And getting data successfully. But I've noticed that this.userList
is undefined
when I was debugging the code (shown on the image). My problem is I can't iterate userList
it says ERROR TypeError: this.userList is not iterable
But on HTML I am using the userList
as a resource to my table. I can see the data that I am getting from DB. So how am I seeing that data if it's undefined and not iterable? I need to use userList
for loop in the same class.
this.service.getUsers().subscribe(data => { this.userList = data; });
testFunction() {
for (let user of this.userList) {
this.selectedUserList.push(user);
}
}
Thank you everyone. I figured it out.
this.service.getUsers().subscribe(data=>{this.userList=data; console.log(data); this.testFunction();});
I called the function within the subscribe worked fine.
If you are calling the testFunction() after subscribing to the data, then you will not get this.userList as undefined. But otherwise you will.
This is because getUsers() return an observable, (since you are subscribing to it) and observables are asynchronous. So by the time getUsers() finishes executing and returns data, which inturn gets assigned to this.userList, the control has already reached the testFunction(). Since the former function hasn't returned yet, the variable this.userList will definitely be undefined.
this.service.getUsers().subscribe(data => {
this.userList = data;
this.testFunction();
});
testFunction() {
for (let user of this.userList) {
this.selectedUserList.push(user);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.