[英]how to make 2 dependent http request in Angular 2
我需要發出2個http請求(第二個依賴於第一個)將用戶憑證插入我的數據庫。
第一個服務獲取用戶憑證( http:// localhost:55978 / FleetViewDBWebService.asmx / ChekCreds?name = name1&subname = subname1 )並檢查用戶是否已經存在,如果存在則返回“ID”,或者“確定” “如果用戶不存在。
然后我需要訂閱第一個服務並獲取返回的值。 如果“ok”調用第二個服務( http:// localhost:55978 / FleetViewDBWebService.asmx / InsertUser?name = name1&subname = subname1&Telephone = 334580021 )
插入用戶憑證,否則返回任何消息。
我調用第一個服務並獲得結果,但我不知道如何添加第二個服務。
有什么想法嗎?
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)
}
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方式是使用switchMap
運算符在觸發第二個請求之前等待第一個請求的響應到達。
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
})
要並行執行請求(對於不相互依賴的請求),請使用forkJoin
靜態運算符 。
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
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.