0

I have a problem with get data to the client using httpClient in my web app. when i check server everything is ok in Postman , but client in angular return empty object. thats my ICalendar interface:

export interface ICalendar {
  calendarName: string;
  userId: number;
  training: Array<{
    trainingTittle: string;
    date: string;
    excercises: Array<{
      excerciseName: string,
      numOfRepeat: number
   }>
  }>;
}

and thats how i get data in service:

 export class CalendarService {
  constructor(private http: HttpClient) { }

  public getAllTrainings() {
    return this.http.get<ICalendar[]>('https://localhost:5001/api/calendar');
  }

and thats how call method looks like:

  ngOnInit(): void {
this.calendarService.getAllTrainings()
  .subscribe(data => {
    this.trainings = data;
  });
console.log(this.trainings);

but log is empty console log of object

and thats how it looks like in database

someone know how to handle it?

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Adrian
  • 13
  • 2

1 Answers1

0

use console.log inside subscribe

ngOnInit(): void {
   this.calendarService.getAllTrainings().subscribe(data => {
    console.log(this.trainings);
    this.trainings = data;
  });

as calling an api is an asynchronous task it will take some time to get response, if you use console.log outside the subscriber then the control flow won't wait for the api call resulting in printing initial value of this.trainings variable,

if you call it inside subscriber the control flow will execute console.log after the api response has been completed hence console.log will get printed with values.

Syed Khizaruddin
  • 435
  • 3
  • 10