我需要发出2个http请求(第二个依赖于第一个)将用户凭证插入我的数据库.
第一个服务获取用户凭证(http://localhost:55978/FleetViewDBWebService.asmx/ChekCreds?name=name1&subname=subname1)并检查用户是否已存在,如果存在则返回“ID”,如果用户不存在则返回“ok”.
然后我需要订阅第一个服务并获取返回的值.
如果“ok”拨打第二项服务(http://localhost:55978/FleetViewDBWebService.asmx/InsertUser?name=name1&subname=subname1&Telephone=334580021)
插入用户凭证,
否则返回任何消息.
有什么想法吗?
service.ts
CheckCreds(value: any) { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); let params = new URLSearchParams(); params.set('name',(value.nom).toString()); params.set('subname',(value.prenom).toString()); return this.http.get(this.checkUri,{ search: params,withCredentials: true }) .map(res => { console.log("++++" + res.text()); return JSON.parse(res.text()); }) .catch(this.handleError) }
component.ts
submitForm($ev,value: any) { $ev.preventDefault(); for (let c in this.valForm.controls) { this.valForm.controls[c].markAsTouched(); } if (this.valForm.valid) { this.Service.CheckCreds(value) .subscribe( res => { string result=JSON.stringify(res); },e => { alert(e); },() => { } ); } }
解决方法
RxJS方式是在发出第二个请求之前使用
the
switchMap
operator等待第一个请求的响应到达.
return this.http.get('url/1') .switchMap(res1 => { // use res1 to further control param of the second call this.http.get('url/2') }) .subscribe(res2 => { //do stuff with the second response })
要并行执行请求(对于不相互依赖的请求),请使用the forkJoin
static operator.
return Observable.forkJoin( this.http.get('url/1'),this.http.get('url/2'),) .subscribe(([res1,res2]) => { // res1 and res2 available after both requests are completed })