I receive data from a function in a service-class, which returns an observable with an array of objects in it. This function, which is basically just a get-request to fetch data from a database, is invoked in the onInit() method in the desired component. Since the function is returning an observable, I subscribe the result and assign it to a separate array in order to process it further in the HTML template. However, the array remains empty, instead of filling with the objects in the observable. Oh, and to narrow down the problem: the connection between the database, server, and application is running.
service.ts
public getCourses() : Observable<Course[]>{
return this.http.get<Course[]>(`${environment.apiUrl}/${this.urlCourses}`)
}
I tried the following in component.ts
:
courseList : Course[] = [];
ngOnInit(): void {
this.courseService
.getCourses()
.subscribe((result : Course[]) => (this.courseList = result));
console.log(this.courseList); // console displays an empty array: []
}
screenshot of the developer console:
However, if I log the result directly within subscribe()
I receive all my objects in a list, like here in component.ts
ngOnInit(): void {
this.courseService
.getCourses()
.subscribe((result : Course[]) => console.log(result)); // console displays an array of objects
}
screenshot of the developer console
I also tried to use observables directly without subscribing them by using the async pipe in the HTML template, but this did not work it for me too.
CodePudding user response:
Your data may not be available when you are logging it. Observable is asynchronous so if the data has not returned from the database by the time the code moves on to your log, it won't be there. Any operation you may need to perform on the data should be within the subscribe callback.
this.courseService
.getCourses()
.subscribe((result : Course[]) => {
this.courseList = result
console.log(this.courseList)
});
CodePudding user response:
If you follow this pattern it should solve your problem.
courseList : Course[]
this.courseService.getCourses().subscribe((result: Course[]) => {
// do stuff with our data here.
// ....
this.courseList = result;
})