Currently, I am facing an issue in my Angular project where subscribing the data to an observable is returning undefined. I have a service method in place that retrieves data from an HTTP request.
public fetchData(): Observable<Data[]> {
const url = `${this.apiUrl}/data`;
return this.httpClient.get<ResponseData>(url).pipe(
map(response => response._embedded.data)
);
}
In addition, there is a component method that fetches the data from the service and assigns it to an "array".
getData() {
// fetching data from the service
this.dataService.fetchData().subscribe(
data => {
this.array = data;
}
);
}
There is another method within the same file that relies on the "array".
processData(){
console.log(this.array)
}
Ultimately, there is a main method that calls both of the aforementioned methods.
executeMethods(){
getData();
processData();
}
The issue arises when calling the componentMethod() first, resulting in an "undefined" value for the array. One potential solution suggests placing the processData() function inside getData() during data subscription. However, due to the need for a loop, this approach is not preferred as it may delay processing time.