如何在Angular2中链接Http调用?

时间:2015-12-05 11:58:21

标签: http angular

我是Angular2和Http Observable的新手。我有一个调用Http服务并返回Observable的组件。比我订阅Observable,它工作正常。

现在,我希望在该组件中,在调用第一个Http服务之后,如果调用成功,则调用其他Http服务并返回该Observable。因此,如果第一次调用不成功,则组件返回Observable,而它返回Observable的第二次调用。

所以,问题是,链接Http调用的最佳方法是什么?有没有优雅的方式,比如monads?

3 个答案:

答案 0 :(得分:83)

您可以使用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运算符的更多信息,请参见here

答案 1 :(得分:5)

使用rxjs完成这项工作是一个很好的解决方案。容易阅读吗?我不知道。

执行此操作且更具可读性(在我看来)的另一种方法是使用 await / async

示例:

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
}

答案 2 :(得分:0)

您也可以链接Promises。按照这个例子

<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>
相关问题