如何在Angular 2中制作2个相关的http请求

hei*_*erg 7 observable rxjs angular

我需要发出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)
来插入用户凭证,否则返回任何消息.

我调用第一个服务并获得结果,但我不知道如何添加第二个服务.

有什么想法吗?

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)


} 
Run Code Online (Sandbox Code Playgroud)

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);
            },
            () => {
            }

            );

    }
}
Run Code Online (Sandbox Code Playgroud)

Laz*_*vić 20

该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
  })
Run Code Online (Sandbox Code Playgroud)

要做到请求并行(是在不依赖于彼此的请求),使用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
  })
Run Code Online (Sandbox Code Playgroud)