Search code examples
arraysangulartypescripthttpobservable

Why the subscribe function does not populate my property?


I have a problem here, i want to populate my property with the data that i get from the backend, but i dont know why my subscribe function does not populate it, check my code:

Here is my app.component.ts code:

export class AppComponent implements OnInit {
  schedulings: Scheduling[] = [];

  constructor(private schedulingService: SchedulingService) {
    this.getSchedulings();
  }

  ngOnInit(): void {
    console.log(this.schedulings);
  }

  getSchedulings(): void {
    this.schedulingService.getSchedulings()
      .subscribe((s) => (this.schedulings = s));
  }
}

And here is my scheduling.service.ts code:

export class SchedulingService {
  private readonly apiUrl = "http://localhost:8080/schedulings";
  
  constructor(private http: HttpClient) { }
  
  getSchedulings(): Observable<Scheduling[]> {
    return this.http.get<Scheduling[]>(this.apiUrl);
  }

}

The way the code is now the console.log function returns a empty list, but when i use a .pipe function with tap(console.log) it print all the schedulings on the console, so the angular gets the data from the backend without errors, but i want to populate the property schedulings with all the data. I know this is a basic and dumb question but i'll be glad if someone can help me.


Solution

  • HTTP requests are asynchronous and take time to complete, if you want code to execute after the request completes, put the code in the subscribe callback.

      getSchedulings(): void {
        this.schedulingService.getSchedulings()
          .subscribe((s) => {
            this.schedulings = s;
            console.log(this.schedulings);
            this.doMoreStuff();
          });
      }
    

    If you prefer a more synchronous style, you can use async / await with firstValueFrom().

      async getSchedulings(): void {
        this.schedulings = await firstValueFrom(this.schedulingService.getSchedulings());
        console.log(this.schedulings);
      }