共享AngularJS服务之间的数据 [英] Sharing data between AngularJS services

查看:96
本文介绍了共享AngularJS服务之间的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有AngularJS共享服务之间的数据吗?

使用情况:不同服务的数据汇总结果
比如我想加载从REST服务一些数据的服务1。然后另一个服务2从另一个REST API增加了额外的数据到Service数据创建数据聚合服务。

Use case: data aggregation from different services
For example I want a service1 that loads some data from a REST Service. Then another service2 adds additional data to the service1 data from another REST API to create a data aggregation service.

我基本上要根据自己使用API​​的服务分开,但仍然有持有到底的所有数据的服务。

I basically want to separate the services based on the APIs that they use, but still have a service that holds all the data in the end.

推荐答案

创建使用 $ Q 推迟库的承诺从2 API REST结合第三个服务呼叫使用 $ q.all()

Create a third service that uses the $q deferred library to combine the promises from the 2 API REST calls using $q.all().

然后通过这第三个服务到控制器作为一个依赖,并使用 $ q.then()的结果结合起来:

Then pass this third service to your controller as a dependency and use $q.then() to combine the results:

var app = angular.module('angularjs-starter');

app.factory('API_1',function($http){    
      return $http.get('dataSource-1.json');   
})

app.factory('API_2',function($http){    
      return $http.get('dataSource-2.json');   
});

app.factory('API_3',function($q,API_1,API_2){ 
 return $q.all([API_1,API_2]);
})
/* add "$q" and "API_3" as dependencies in controller*/
app.controller('MainCtrl', function($scope,$q,API_3) {

  $q.when(API_3).then(function(results) {
    /* combine the 2 API results arrays*/
    $scope.combinedData=[results[0].data,results[1].data];    

  });    


});

DEMO: Plunker演示

DEMO: Plunker Demo

这篇关于共享AngularJS服务之间的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆