如何在Angular 2中创建2个依赖的http请求
问题描述:
我需要创建2个http请求(第二个依赖于第一个请求),以将用户credentiels插入到我的数据库中。如何在Angular 2中创建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
})
我试图做类似的事情,有人帮助我。检查https://stackoverflow.com/questions/44831278/angular2-subscribe-inside-subscribe – Rama