【问题标题】:Angular2: How to make several GET requests at onceAngular2:如何一次发出多个 GET 请求
【发布时间】:2016-06-15 19:58:45
【问题描述】:

使用 promise JS 库 (https://github.com/stackp/promisejs) 我可以做到这一点:

promise.join([
    promise.get('/settings'),
    promise.get('/translations'),
    promise.get('/main-data')
]).then(function(results) {
    console.log(results);
});

现在我需要用 Angular2 来做这件事。因此,我使用 getSettingsgetTranslations 等方法创建了一个服务 - 但我如何在使用此服务的组件中 join 它们?

(并以这样的方式加入他们,当且仅当所有请求完成时 - 我将运行一个使用所有响应的功能?)

【问题讨论】:

    标签: ajax http angular promise


    【解决方案1】:

    您可以为此使用forkJoin 运算符

    import {Observable} from 'rxjs/Rx';
    
    
    
    //...some code
    
     Observable.forkJoin( 
        this.http.get('/settings').map((res:Response) => res.json()),
        this.http.get('/translations').map((res:Response) => res.json())
      )
      .subscribe(data => {
        console.log(data[0], data[1]);
      });
    

    【讨论】:

      【解决方案2】:

      答案并没有解决问题,主要是我不明白如何获取数据in组件。但它仍然很好地指导了我:)

      所以,这是最终的代码:

      // Service - "AppService.ts":
      import {Observable} from 'rxjs/Rx';
      
      export class AppService {
      
          getAllData() {
              return Observable
                  .forkJoin(
                      this._http.get('/settings').map(res => res.json()),
                      this._http.get('/translations').map(res => res.json())
                  )
          }
      
      }
      
      // Component - "AppComponent.ts":
      import {AppService} from './app.service';
      
      export class AppComponent {
      
          AllData = {};
      
          appService
              .getAllData()
              .subscribe(
                  data => {
                      console.log('Responses from AJAX:');
                      console.log(data);
                      this.AllData = JSON.stringify(data)
                  },
                  error => alert(error)
              );
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-10
        • 2018-11-05
        • 1970-01-01
        • 2019-09-07
        • 2021-06-04
        • 2021-08-04
        • 1970-01-01
        相关资源
        最近更新 更多