简体   繁体   English

如何在angular 2中同步调用http

[英]How to make synchronous http calls in angular 2

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.例如,有一个queryArr参数。 What does it do?它有什么作用?

Anyway, I need a little bit of a guidance about how to make synchronous http calls in simplest way.无论如何,我需要一些关于如何以最简单的方式进行同步 http 调用的指导。 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 .例如,有可观察对象oxoy Data of the request being called in oy is depended on the data comes from ox : oy中调用的请求数据取决于来自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")
        );
    }
);

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.记得上次(javascript我做的不多,是个小菜鸟),在我订阅oy的scope里, xData或者yData都看不到了。 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?有没有“好的”解决方案或更好的方法来做这种事情?

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.我认为您可以查看flatMap运算符来执行 HTTP 请求,等待其响应并执行另一个。

Here is a sample:这是一个示例:

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
  });
}

If you want to have access to both results in the subscribe method, you could leverage Observable.forkJoin and Observable.of :如果您想在subscribe方法中访问这两个结果,您可以利用Observable.forkJoinObservable.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];
  });
}

如果您在此处编写@khushboo 并向我们展示您的函数/代码,您的问题将更容易理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM