I'm working on an Angular project. but I have problem when I subscribe the data to observable is returning undefined
and I have a service method that returns data from HTTP.
public serviceMethod(): Observable<WordList[]> {
const url = `${this.baseUrl}/wordLists`;
return this.httpClient.get<GetResponseWordList>(url).pipe(
map(response => response._embedded.wordLists)
);
}
and a component method that takes the data from the service and assigns it to an "array"
componentMethod() {
// get from the service
this.otherService.serviceMethod().subscribe(
data => {
this.array = data;
}
);
}
I have another method in the same file that use the "array"
secondMethod(){
console.log(this.array)
}
Finally, I have the main method that uses both the last two methods.
mainMethodMethod(){
componentMethod();
secondMethod();
}
the componentMethod() is run first. However, always get an "undefined" value of the array
one solution is to put the secondMethod() inside componentMethod() when to subscribe the data. But I don't want to do that because I need to use a loop and that will take too long.
You have to call your secondMethod in the subscribe function after the data variable.
It gets undefined since its asynchronous, it has to wait for the data to finish loading then call your next functions.
If you call it after the first method then the 2nd method will get executed without the first
I think that you should clarify this part of your question :
"But I don't want to do that because I need to use a loop and that will take too long"
What is the loop you need to use ? Because it's constraint that is maybe the base of the problem ...
With what you explained, I see (at least) this solution :
componentMethod() {
// get from the service
return this.otherService.serviceMethod().pipe(
map(data => {
this.array = data;
})
);
}
mainMethodMethod(){
componentMethod().subscribe(() => {
secondMethod();
})
}