Retrieving data from a server in Angular using an Observable can result in an undefined initial value if attempted immediately.
@Injectable() export class EventService { ... getEventList(): Observable<any> { ... return this.http.get(...).map(...).catch(...); } }
export class EventComponent { myEvents: any; ngOnInit() { this.es.getEventList().subscribe((response) => { this.myEvents = response; }); console.log(this.myEvents); // Initially undefined } }
The HTTP request is asynchronous, meaning the console.log(this.myEvents) line executes before the response arrives.
Handle the response only after it arrives by using the subscribe callback.
ngOnInit() { this.es.getEventList().subscribe((response) => { this.myEvents = response; console.log(this.myEvents); // Not undefined }); }
The above is the detailed content of How Do I Handle Asynchronous Responses from Observables in Angular?. For more information, please follow other related articles on the PHP Chinese website!