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

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

问题描述

有没有办法在 AngularJS 中的服务之间共享数据?

用例:来自不同服务的数据聚合
例如,我想要一个从 REST 服务加载一些数据的 service1.然后另一个 service2 从另一个 REST API 向 service1 数据添加附加数据以创建数据聚合服务.

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];    

  });    


});

演示:Plunker 演示

DEMO: Plunker Demo

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

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