ajax - 链接 AJAX 请求 - Angular 2 和 ES2015 Promises

标签 ajax typescript angular

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

(伪代码)

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

我知道如何在 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);
            });
    });
}

然而,第二个示例中的代码对我来说看起来更丑陋且可读性更差。

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

按照该逻辑,我可以将所有 GET 请求(第 2 部分)包装在 promises 中,而不是将其链接起来,但同样,这似乎不是一种干净利落的方式。

问题 2:我如何在 angular 2 中很好地链接请求,而不用将每个请求包装在 promise 中。

最佳答案

您可以为此利用可观察对象。没有必要使用 promise ...

串联(相当于 promise 链):

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

并行(相当于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];
});

关于错误处理和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);
     });
}

关于ajax - 链接 AJAX 请求 - Angular 2 和 ES2015 Promises,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38099177/

相关文章:

angular - 为什么 ContentChild 未定义?

jquery - rails : how to update a has_many :through relation via jQuery?

jquery - 如何使用 Ajax 获取在输入字段中输入的内容?

ajax - Chrome 无法 POST 到 https,但 GET 使用自签名的 SSL 证书?

typescript type is not assignable to type `symbol` 错误

javascript - Angular 5 : how to make dynamically created components draggable with jsPlumb?

javascript - AJAX 调用完成时重置 Bootstrap 加载状态按钮

Angular 8 - 按值类型对递归树组件进行排序

javascript - Angular 输出不起作用 - instance[output.propName].subscribe 不是函数

javascript - 在 PrimeNG 中扩展多个面板时如何修复损坏?