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.

0

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

1 Comment

Then what is the solution?
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.

Comments

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);
}); 

1 Comment

I want to use "rooms" in the rest of the code. How do I get to update it globally?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.