在工厂中重复使用来自$ http的数据 [英] Reuse data from $http in factory

查看:63
本文介绍了在工厂中重复使用来自$ http的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Angular.js中的控制器之间共享数据的适当方法是使用工厂或服务.

I understand that the appropriate method to share data between controllers in Angular.js is by using Factories or Services.

app.controller('Controller1', function($scope, DataService) {
  DataService.getValues().then(
    function(results) {
      // on success
      console.log('getValues onsuccess');
    });
});

app.controller('Controller2', function($scope, DataService) {
  DataService.getValues().then(
    function(results) {
      // on success
      console.log('getValues onsuccess');
    });
});

app.factory('DataService', function($http) {
  var getValues = function() {
    console.log('making http request');
    return $http.get("/api/getValues");
  };

  return {
    getValues: getValues
  }
});

我有两个控制器在工厂中两次调用相同的方法 一切都很好,一切正常.我唯一的顾虑是,两次发出相同的请求似乎有点多余吗?
使用$ broadcast会更好吗?
或者我可以以不同的方式构造我的代码,以便仅调用一次该服务吗?

I have two controllers calling the same method in a factory twice and this is perfectly fine and everything is working as it should. My only concer is that it seems a bit unecessary to make the same request twice?
Would the use of $broadcast be a better approach?
Or could i structure my code differenty so that the service is called only once?

推荐答案

您可以将请求的结果存储在工厂中,然后检索这些结果.

You could store the results of the request in the factory and retrieve those instead.

app.factory('DataService', function($http) {
  var values;
  var requestValues = function() {
    console.log('making http request');
    $http.get("/api/getValues").then(
        function(results){
            values = results;
        });
  };
  var getValues = function() {
    return values;
  };
  return {
    requestValues : requestValues,
    getValues: getValues
  }
});

这篇关于在工厂中重复使用来自$ http的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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