zoukankan      html  css  js  c++  java
  • Angular7 HttpClient处理多个请求

    1. MergeMap - 串联请求

    • 后一个请求需要前一个请求的返回结果时,需要使用串联请求。

    • 可以使用MergeMap实现, 优势是减少嵌套,优化代码;

    代码如下:

    import {HttpClient} from '@angular/common/http';
    import {mergeMap} from 'rxjs';
    
    @Component({
       ...
    })
    export class HttpComponent implements OnInit {
    
    
      constructor(private http: HttpClient) { }
    
    
      ngOnInit() {
        // 串联请求, 前面请求会影响后面的请求,前面请求未请求到,后面请求中断;
        const httpThis = this;
        httpThis.http.get('/api/token').
          pipe(
          map(token => {
            return token;
          }),
          mergeMap((tokenRes: any) => { // tokenRes接收的是token数据
            return httpThis.http.get(`/api/user?token=${tokenRes}`)
              .pipe((user) => {
                return user;
              });
          }),
          mergeMap((userRes: any) => { // userRes接收的是user数据
            return httpThis.http.get(`api/data?user=${userRes}`)
              .pipe((data) => {
                return data;
              });
          }))
          .subscribe((resp) => { // resp接收的是data数据
            console.log('最终结果resp是最后一个mergeMap的data');
          });
      }
    }
    

    2. ForkJoin - 并联请求

    • 多个请求,无所谓先后顺序,等到全部请求完成后执行一定的操作时,需要使用并联请求;

    • 可以使用ForkJoin,和promise方法效果一样,好处是:可以减少嵌套,优化代码;

    代码如下:

    import {HttpClient} from '@angular/common/http';
    import {forkJoin} from 'rxjs';
    
    @Component({
       ...
    })
    
    
    export class HttpComponent implements OnInit {
    
    
      constructor(private http: HttpClient) { }
    
    
      ngOnInit() {
         
        // 并联请求
        const post1 = this.requestData1();
        const post2 = this.requestData2();
        forkJoin([post1, post2])
          .subscribe((data: any) => {
            const postResult1 = data[0]; // '/api/post1的返回结果'
            const postResult2 = data[1]; // '/api/post2的返回结果'
          });
      }
    
    
      // 并联请求1
      requestData1() {
        return this.http.get('/api/post1')
          .pipe((data) => {
            return data;
          });
      }
    
    
      // 并联请求2
      requestData2() {
        return this.http.get('/api/post2')
          .pipe((data) => {
            return data;
          });
      }
    }
    

      

  • 相关阅读:
    eclipse如何与git 配合工作。
    git托管代码(二)
    PPC2003 安装 CFNET 3.5成功
    我的Window Mobile WCF 項目 第三篇 WM窗体设计
    我的Window Mobile WCF 項目 第一篇Mobile开发和WinForm开发的区别
    我的Window Mobile WCF 項目 第七天
    我的Window Mobile WCF 項目 第二篇 WindowsMobile访问WCF
    WCF 用vs2010 和 vs2008的简单对比测试
    vs2010beta1 和 搜狗输入法 冲突,按下 Ctrl 键就报错,重装搜狗解决
    我的Window Mobile WCF 項目 第六天 (二)
  • 原文地址:https://www.cnblogs.com/xiaxianfei/p/13156857.html
Copyright © 2011-2022 走看看