angular - How to wait until one of many possible observables returns before continuing -
i have switch statement makes different http call based on input.
it looks 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 after these have statement save entry:
this.storageservice.saveentry(myobject);
but @ time entry saved, not have name property set.
what proper way wait 1 of these async calls return before saving entry?
if must use switch statement, perhaps have each branch return observable instead, set myobject.name
in subscribe()
or utilize operators such do , switchmap
pass value 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 helps!
wiki
Comments
Post a Comment