链接AJAX请求 - Angular 2和ES2015 Promises

时间:2021-06-21 19:41:29

In Angular 1 I could do something like:

在Angular 1中我可以做类似的事情:

(pseudo code)

/* part 1 */
function myFn1(){
    var x = $http.get('myurl');

    x.then(
        () => {}, // do something here
        () => {} // show error here
    );

    return x;
}

/* part 2 */
myFn1().then(()=>{
  $q.all($http.get('url'), $http.get('url2'), $http.get('url3'))
    .then(()=>{  /* do something */  });
});

I know how to replicate part 1 in Angular 2

我知道如何在Angular 2中复制第1部分

let myFn = () => {
    return new Promise((res, rej) => {
        this.http.get('myurl')
            .subscribe((success) => {
                // do something here
                res(success);
            }, (error) => {
                // show error here
                rej(error);
            });
    });
}

However the code in 2nd example looks much uglier and much less readable for me.

然而,第二个例子中的代码看起来更加丑陋,对我来说可读性也差得多。

Question 1: Can I do it better/nicer way?

问题1:我可以做得更好/更好吗?

Following that logic I can wrap all GET requests (part 2) in promises and than chain it but again this doesn't seem to be nice and clean way of doing that.

遵循这个逻辑,我可以将所有GET请求(第2部分)包装在promises中,然后将其链接起来,但是再次这似乎并不是很好而且干净的方式。

Question 2: how I can nicely chain requests in angular 2 without wrapping every single request in promise.

问题2:如何在角度2中很好地链接请求而不包含承诺中的每个请求。

2 个解决方案

#1


1  

As for part2, you can still use Promises:

至于part2,你仍然可以使用Promises:

myFn1().then(() => {
  return Promise.all(
    $http.get('url').toPromise().then(res => res.json()),
    $http.get('url2').toPromise().then(res => res.json()),
    $http.get('url3').toPromise().then(res => res.json())
  ).then(() => {
    /* do something */
  });
});

#2


3  

You can leverage observables for this. It's not necessary to use promises...

您可以利用observables。没有必要使用承诺......

In series (equivalent to promise chaining):

串联(相当于承诺链):

this.http.get('http://...').map(res => res.json())
    .flatMap(data => {
      // data is the result of the first request
      return this.http.get('http://...').map(res => res.json());
    })
    .subscribe(data => {
      // data is the result of the second request
    });

In parallel (equivalent to Promise.all):

并行(相当于Promise.all):

Observable.forkJoin([
  this.http.get('http://...').map(res => res.json()),
  this.http.get('http://...').map(res => res.json())
])
.subscribe(results => {
  // results of both requests
  var result1 = results[0];
  var result2 = results[1];
});

Regarding error handling and part1, you can migrate things like this:

关于错误处理和part1,您可以迁移这样的事情:

/* part 1 */
function myFn1(){
  return this.http.get('myurl').map(res => res.json())
     .map(data => {
       // do something
       return data;
     })
     .do(data => {
       // do something outside the data flow
     })
     .catch(err => {
       // to throw above the error
       return Observable.throw(err);
     });
}

#1


1  

As for part2, you can still use Promises:

至于part2,你仍然可以使用Promises:

myFn1().then(() => {
  return Promise.all(
    $http.get('url').toPromise().then(res => res.json()),
    $http.get('url2').toPromise().then(res => res.json()),
    $http.get('url3').toPromise().then(res => res.json())
  ).then(() => {
    /* do something */
  });
});

#2


3  

You can leverage observables for this. It's not necessary to use promises...

您可以利用observables。没有必要使用承诺......

In series (equivalent to promise chaining):

串联(相当于承诺链):

this.http.get('http://...').map(res => res.json())
    .flatMap(data => {
      // data is the result of the first request
      return this.http.get('http://...').map(res => res.json());
    })
    .subscribe(data => {
      // data is the result of the second request
    });

In parallel (equivalent to Promise.all):

并行(相当于Promise.all):

Observable.forkJoin([
  this.http.get('http://...').map(res => res.json()),
  this.http.get('http://...').map(res => res.json())
])
.subscribe(results => {
  // results of both requests
  var result1 = results[0];
  var result2 = results[1];
});

Regarding error handling and part1, you can migrate things like this:

关于错误处理和part1,您可以迁移这样的事情:

/* part 1 */
function myFn1(){
  return this.http.get('myurl').map(res => res.json())
     .map(data => {
       // do something
       return data;
     })
     .do(data => {
       // do something outside the data flow
     })
     .catch(err => {
       // to throw above the error
       return Observable.throw(err);
     });
}