Reputation: 384
I have switch statement that makes a different http call based on the input.
It looks something like this:
switch(myObject.type){
case 'Type1':
myObject.name = this.service1.getName(myObject.id);
break;
case 'Type2':
myObject.name = this.service2.getName(myObject.id);
break;
case 'Type3':
myObject.name = this.service3.getName(myObject.id);
break;
}
and immediately after these I have a statement to save the entry:
this.storageService.saveEntry(myObject);
but at the time the entry is saved, it does not have the name property set.
What is the proper way to wait for any one of these async calls to return before saving the entry?
Upvotes: 0
Views: 415
Reputation: 38847
If you must use the switch statement, you could perhaps have each branch return the observable instead, then set myObject.name
in the subscribe()
or utilize operators such as do and switchMap
to pass the value to this.storageService.saveEntry()
.
foo(): Observable<any> {
switch(myObject.type){
case 'Type1':
return this.service1.getName(myObject.id);
break;
case 'Type2':
return this.service2.getName(myObject.id);
break;
case 'Type3':
return this.service3.getName(myObject.id);
break;
}
}
bar() {
foo()
.do(name => myObject.name = name)
.switchMap(name => this.storageService.saveEntry(myObject))
.subscribe(response => console.log(response);
}
Hopefully that helps!
Upvotes: 1