Angular.js - 将http.get(array)转换为过滤器

时间:2015-07-09 04:59:58

标签: angularjs database variables

我只想将从http.get()返回的数组传递给变量,以便在工厂中过滤它们。 (类似于聊天 - 来自离子的例子)

这是我的工厂:

.factory('pizzaService', function($http) {
  return {
    all: function() {
      // Return promise (async callback)
      return $http.get("http://localhost/soundso/www/php/load_Pizzas.php");
    },
    get: function(pizzaID) {
      for (var i = 0; i < pizzas.length; i++) {
        if (pizzas[i].id === parseInt(pizzaID)) {
          return pizzas[i];
        }
      }
      return null;
    }
  };
});

在get函数中,它不知道比萨是什么,因为它不像&#34; var pizzas = http.get(...)&#34;,但这并不是什么意思。工作。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

$ http.get方法返回一个future对象。要获取响应内容,您必须定义成功回调并将结果存储在变量中。它会给你这样的东西(我没有测试它):

.factory('pizzaService', function($http) {
  var pizzas;
  // your data are got from the URL only once when the factory is invoked. may be moved elsewhere if the Url is invoked several times
  function getDataFromServer(){
    $http.get("http://localhost/soundso/www/php/load_Pizzas.php").
      success(function(data, status) {
        pizzas=data;
      }).error(function(data, status) {
        // called asynchronously if an error occurs
      });
  }
  //the first call on factory initialisation initialize the pizzas variable
  getDataFromServer();
  return {
    getAll : function(){
      return pizzas;
    },
    get: function(pizzaID) {
      for (var i = 0; i < pizzas.length; i++) {
        if (pizzas[i].id === parseInt(pizzaID)) {
          return pizzas[i];
        }
      }
      return null;
    }
  };
});

您可能还想添加一个额外的方法来刷新服务器上的数据,即:按需启动$ http请求:

...
return {
    refresh : function(){
      getDataFromServer();
    },
    getAll : ...
    get : ...
};