首页 文章

如何在Angular2中链接Http调用?

提问于
浏览
52

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

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

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

3 回答

  • 3

    您可以使用 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

  • 0

    使用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
    }
    
  • 82

    你也可以链接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>
    

相关问题