How may I block a constructor, to wait for an Http call to return data?
constructor() {
this.initRestData().subscribe();
// wait for data to be read
this.nextStep();
}
The data retreived by the initRestData() call is needed by other services/components in the application. I only have to do this at startup. If there is a better way to handle this then Observable that would be ok too.
You could chain the calls either inside the subscribe
or in a do
-operator:
constructor() {
this.initRestData()
.do(receivedData => this.nextStep(receivedData)})
.subscribe();
}
For the case that other services rely on this.nextStep()
as well, you should implement this as a stream as well:
private initialData$ = new BehaviorSubject<any>(null);
constructor() {
this.initRestData()
.do(data => this.initialData$.next(data))
.switchMap(() => this.nextStep())
.subscribe();
}
nextStep(): Observable<any> {
return this.initialData$
.filter(data => data != null)
.take(1)
.map(data => {
// do the logic of "nextStep"
// and return the result
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.