如何链的Http在Angular2电话?如何链的Http在Angular2电话?(How to ch

2019-05-11 02:45发布

我是新来Angular2和HTTP观测。 我有一个要求HTTP服务,并返回可观测的组成部分。 比我订阅可观察的,它工作正常。

现在,我想,在这部分,要求第一个HTTP服务后,如果调用成功,调用其他HTTP服务,并返回可观察的。 所以,如果第一个电话是不是成功的组件返回观察的,相反,它返回可观察到第二个电话的。

所以,问题是,什么是连锁HTTP调用的最好方法? 是否有任何优雅的方式,例如像单子?

Answer 1:

您可以使用做到这一点mergeMap运营商

首先导入操作如下:

import 'rxjs/add/operator/mergeMap';

那么这里是你如何链上的两个呼叫:

this.http.get('./customer.json')
            .map((res: Response) => res.json())
            .mergeMap(customer => this.http.get(customer.contractUrl))
            .map((res: Response) => res.json())
            .subscribe(res => this.contract = res);

这里一些细节: http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http

关于mergeMap操作的更多信息,可以发现这里



Answer 2:

使用rxjs做的工作是一个非常好的解决方案。 它是否易于阅读? 我不知道。

另一种方式来做到这一点,更具有可读性(在我看来)是使用的await /异步

例如:

async getContrat(){
    //get the customer
    const customer = await this.http.get('./customer.json').toPromise();

    //get the contract from url
    const contract = await this.http.get(customer.contractUrl).toPromise();

    return contract; // you can return what you want here
}

然后调用它:)

this.myService.getContrat().then( (contract) => {
  // do what you want
});

或在一个异步函数

const contract = await this.myService.getContrat();

您也可以使用try / catch来管理错误:

let customer;
try {
  customer = await this.http.get('./customer.json').toPromise();
}catch(err){
   console.log('Something went wrong will trying to get customer');
   throw err; // propagate the error
   //customer = {};  //it's a possible case
}


Answer 3:

你也可以连锁的承诺了。 按照本例

<html>
<head>
  <meta charset="UTF-8">
  <title>Chaining Promises</title>
</head>
<body>
<script>
  const posts = [
    { title: 'I love JavaScript', author: 'Wes Bos', id: 1 },
    { title: 'CSS!', author: 'Chris Coyier', id: 2 },
    { title: 'Dev tools tricks', author: 'Addy Osmani', id: 3 },
  ];

  const authors = [
    { name: 'Wes Bos', twitter: '@wesbos', bio: 'Canadian Developer' },
    { name: 'Chris Coyier', twitter: '@chriscoyier', bio: 'CSS Tricks and Codepen' },
    { name: 'Addy Osmani', twitter: '@addyosmani', bio: 'Googler'},
  ];

  function getPostById(id) {
    // create a new promise
    return new Promise((resolve, reject) => {
       // using a settimeout to mimic a database/HTTP request
       setTimeout(() => {
         // find the post we want
         const post = posts.find(post => post.id == id);
         if (post) {
            resolve(post) // send the post back
         } else {
            reject(Error('No Post Was Found!'));
         }
       },200);
    });
  }

  function hydrateAuthor(post) {
     // create a new promise
     return new Promise((resolve, reject) => {
       // using a settimeout to mimic a database/http request
       setTimeout(() => {
         // find the author
         const authorDetails = authors.find(person => person.name === post.author);
         if (authorDetails) {
           // "hydrate" the post object with the author object
           post.author = authorDetails;
           resolve(post); 
         } else {
       reject(Error('Can not find the author'));
         }
       },200);
     });
  }

  getPostById(4)
    .then(post => {
       return hydrateAuthor(post);
    })
    .then(post => {
       console.log(post);
    })
    .catch(err => {
       console.error(err);
    });
</script>
</body>
</html>


文章来源: How to chain Http calls in Angular2?
标签: http angular