加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 18:00:09 所属栏目:安全 来源:网络整理
导读:我需要发出2个http请求(第二个依赖于第一个)将用户凭证插入我的数据库. 第一个服务获取用户凭证(http://localhost:55978/FleetViewDBWebService.asmx/ChekCreds?name=name1subname=subname1)并检查用户是否已存在,如果存在则返回“ID”,如果用户不存在则返回
我需要发出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
  })

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读