角度合并来自不同方法的数据

时间:2019-12-02 12:21:00

标签: javascript angular rxjs observable

我有来自三种不同服务的数据,我想将来自所有服务的数据合并为一种方法

this.data1 = this.activity1Service.getAllMonth(); 
this.data2 = this.activity2Service.getAllMonth();
this.data3 = this.activity3Service.getAllMonth();

this.alldata =  concat (this.data1,this.data2,this.data3); 

并作为可观察者呼叫

GetAllData(): Observable<Data[]>{


  return (this.alldata);

  }

然后执行ngOnInit()


ngOnInit() {

    this.dataService.getAllData().subscribe(aldata => this.AllData = aldata);
  } 

我不确定如何将来自不同服务的数据合并为一种方法,任何人都可以帮忙。

4 个答案:

答案 0 :(得分:1)

我想你想要这样的东西:

import { Observable, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';

  getAllData(): Observable<any[]>{
    return combineLatest([
      this.activity1Service.getAllMonth(), 
      this.activity2Service.getAllMonth(), 
      this.activity3Service.getAllMonth()
    ]).pipe(map([data1, data2, data3] => [...data1, data2, data3]))
  }

combineLatest将结合每个可观察到的最新发射值,在map中,您可以根据需要选择一些逻辑来映射数据。

答案 1 :(得分:1)

您可以使用forkJoin

  

forkJoin等待每个HTTP请求完成并将所有   每个HTTP调用返回到单个可观察数组中的可观察对象   最后返回该可观察数组。

类文件

getAllData() {
        this.data1 = this.activity1Service.getAllMonth(); 
        this.data2 = this.activity2Service.getAllMonth();
        this.data3 = this.activity3Service.getAllMonth();
        return forkJoin([this.data1, this.data2, this.data3]);
}


ngOnInit() {

    this.getAllData().subscribe(aldata => {
        console.log(data);
        this.AllData = aldata
    });
} 

答案 2 :(得分:0)

您可以使用$ q.all()将多个API的承诺合并到单个响应对象中,请参见下面的代码段

var app = angular.module('app1', []);


app.factory('json',function($q,$http){
  
  return function(files){
    
    var promises = [];
    
    angular.forEach(files, function(file){
      
      var deffered  = $q.defer();
  
      $http({
        url : file,
        method: 'GET'
      }).
      success(function(data){
        deffered.resolve(data);
      }).
      error(function(error){
          deffered.reject();
      });
      
      promises.push(deffered.promise);

    })
    
    return $q.all(promises);
  }
  
});

app.controller('MainCtrl', function($scope,json) {
  $scope.name = 'World';
  
  json([[1,2,3], [4,5,6]]).then(function(datas){
    $scope.a = datas[0]
    $scope.b = datas[1]
  })

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
  <body ng-app="app1" >
    <div ng-controller="MainCtrl">
    <pre>{{a | json}}</pre>
    <pre>{{b | json}}</pre>
    </div>
  </body>

答案 3 :(得分:0)

concat 不等待从所有可观察对象收到的响应,而是完成一个可观察对象并发送其响应,然后处理下一个响应。因此它不会合并可观察对象的响应。

您可以将concat看作是ATM上的一条线路,在前一个事务完成之前,下一个事务(订阅)才能开始!有关更多详细信息,https://www.learnrxjs.io/operators/combination/concat.html

您可能必须使用 forkJoin zip 运算符,该运算符等待所有可观察对象的响应并将其组合以产生最终结果,有关更多详细信息,< / p>

https://scotch.io/tutorials/rxjs-operators-for-dummies-forkjoin-zip-combinelatest-withlatestfrom

相关问题