如何在Angular 2中进行同步http调用 [英] How to make synchronous http calls in angular 2

查看:452
本文介绍了如何在Angular 2中进行同步http调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经在此处提出了此问题.但是,由于提问者的应用程序上下文涉及的问题太多,因此我无法理解其基本知识.例如,有一个queryArr参数.它是做什么的?

This question has already been asked here. However, since the asker's application context is involved too much in the question, I couldn't understand the basics. For example, there is a queryArr parameter. What does it do?

无论如何,我需要一些有关如何以最简单的方式进行同步http调用的指南.我想出的解决方案是,必须以嵌套"顺序订阅可观察对象.例如,有观察值oxoy.在oy中被调用的请求的数据取决于来自ox的数据:

Anyway, I need a little bit of a guidance about how to make synchronous http calls in simplest way. The solution I came up with is that one has to subscribe to observables in a "nested" order. For example, there are observables ox and oy. Data of the request being called in oy is depended on the data comes from ox:

xData: string = "";
yData: string = "";  

ox.subscribe(
    data => {xData = data;},
    error => console.log(error),
    () => {
        oy.subscribe(
            data => {yData = xData*data;},
            error => console.log(error),
            () => console.log("aaa")
        );
    }
);

我记得上次(我不使用JavaScript太多,并且是个新手),在我订阅oy的范围内,再也看不到xDatayData了.请纠正我,如果我错了,请指向正确的方向.

Last time I remember (I don't do javascript much, and am a little newbie), in the scope where I subscribed to oy, the xData or yData cannot be seen anymore. Please correct me and point me to the right direction if I am wrong.

是否有任何精细"解决方案或更好的方法来完成这种事情?

Is there any "fine" solution or better way to do this kind of thing?

推荐答案

我认为您可以看看flatMap运算符来执行HTTP请求,等待其响应并执行另一个请求.

I think that you could have a look at the flatMap operator to execute an HTTP request, wait for its response and execute another one.

以下是示例:

executeHttp(url) {
  return this.http.get(url).map(res => res.json());
}

executeRequests() {
  this.executeHttp('http://...').flatMap(result => {
    // result is the result of the first request
    return this.executeHttp('http://...');
  }).subscribe(result => {
    // result is the result of the second request
  });
}

如果要使用subscribe方法访问两个结果,则可以利用Observable.forkJoinObservable.of:

If you want to have access to both results in the subscribe method, you could leverage Observable.forkJoin and Observable.of:

executeRequests() {
  this.executeHttp('http://...').flatMap(result => {
    // result is the result of the first request
    return Observable.forkJoin(
      Observable.of(result),
      this.executeHttp('http://...')
    ).subscribe(results => {
    // results is an array of the results of all requests
    let result1 = results[0];
    let result2 = results[1];
  });
}

这篇关于如何在Angular 2中进行同步http调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆