0

I wrote a service:

loadroom() : Observable<any[]>{
    return this.http.get(this.roomUrl)
        .pipe(
            map((response: any) => {
                let resources = response;
                return resources.map(function(room:any) {
                    return {id: room.id, title: room.title, eventcolor: room.eventColor};
                });
            })
        );
}

Then I use this service in a component

rooms: any[] = [];       
ngOnInit() {
    this.schedulerService.loadroom().subscribe(response => this.rooms = response);
    console.log(this.rooms);
}

I didn't see data in the array. In console I get an empty array []

But if I use

this.schedulerService.loadroom().subscribe(response => {console.log(response)});

I get the data.

Gilsido
  • 542
  • 1
  • 3
  • 11
Alex
  • 53
  • 12

3 Answers3

6

Yes, this is completely the expected behavior, subscribeis asynchronous, meaning that calling it won't block the execution of the code, it won't wait for it to finish before executing the next line. So

this.schedulerService.loadroom().subscribe(response => this.rooms=response);
    console.log(this.rooms);

Triggers the log before the subscription finished

Gilsido
  • 542
  • 1
  • 3
  • 11
0

Subscribe is asynchronous. It's likely the execution isn't finished : you need to work in the chained event to keep the flow at this point. Anything you need to do with this.rooms need to be in the subscribe event.

RoadEx
  • 543
  • 2
  • 12
0

It is because Observable are asynchronous. Meaning console.log(this.rooms); happen before response => this.rooms=response.

So the correct way of using it is:

this.schedulerService.loadroom().subscribe(response => {
  this.rooms = response;
  console.log(this.rooms);
}); 
Ambroise Rabier
  • 3,636
  • 3
  • 27
  • 38