Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

angular2 observables - 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. What does it do?

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...