typescript - Wait for a Subscription and a Promise in Angular 4 -
i'm new angular 4, accept may better off changing approach.
what have this:
ngoninit() { this.route.parammap .switchmap((params: parammap) => { var id = +params.get('id'); return this.service.getone(id); }).subscribe(data => { if (data.clientid === 0) { data.clientid = +this.route.snapshot.queryparams["parentid"]; } this.model = data; },); // subscription this.lookupservice.getlist("clients").then(data => { this.clients = data; }); // promise }
on client-side, need make server call, when have data both of calls above. in other words, need subscription
complete (well, not complete set value) , promise
complete.
is there promise.all
work ensure this.model
has been set in subscription
call?
edit: run these in series, performance reasons, want run them in parallel.
edit 2: promise
intended load lookup data populate dropdown once. subscription
intended change main model on each change of "id" in url .
you can use observable.forkjoin
, equivalent promise.all
.
observable.forkjoin(this.route.parammap .switchmap((params: parammap) => { var id = +params.get('id'); return this.service.getone(id); }), observable.frompromise(this.lookupservice.getlist("clients"))) .subscribe((arrayofresults) => { [firstcallresult, secondcallresult] = arrayofresults; this.model = firstcallresult; });
edit:
to fulfill part updating parameters, can use observable.combinelatest
operator:
about observable.combinelatest
since emits whenever 1 of source observables emits, subscribe block executed. since other observable promise complete , not emit more values this.lookupservice.getlist() not called again.
observable.combinelatest(this.route.parammap .switchmap((params: parammap) => { var id = +params.get('id'); return this.service.getone(id); }), observable.frompromise(this.lookupservice.getlist("clients"))) .subscribe((arrayofresults) => { [firstcallresult, secondcallresult] = arrayofresults; this.model = firstcallresult; // whatever else needed });
wiki
Comments
Post a Comment