将硬编码数组更改为$ http回调

时间:2014-12-15 13:31:44

标签: javascript arrays angularjs global-variables ionic-framework

我想将我的服务从硬编码静态数组更改为$ http调用返回的数组。我试图在下面这样做,但它不起作用。

我可以确认从http返回的数据是否正常工作并返回正确的数据(我已将链接用于问题目的)。

我没有收到错误消息,因此此时无法提供任何进一步的信息,但我想知道的是我是否以正确的方式这样做。

此刻我的头靠在墙上执行如此简单的任务......

hardcorded array:

.factory('Cards', function($http){
  var cardTypes = [
    {id: 1, USECASE_NAME: "Frank", USECASE_IMAGE: 'img/Frank.png', USECASE_DESC:"This is frank the bank card, He helps people all over the world make millions of transactions each year!", done: true },
    {id: 2, USECASE_NAME: "John Lewis", USECASE_IMAGE: 'img/JohnLewis.png', USECASE_DESC:"John Lewis is one of the biggest retailers in the United Kingdom with a very proud reputation", done: true },
    {id: 3, USECASE_NAME: "Generali", USECASE_IMAGE: 'img/Generali.png', USECASE_DESC:"Generali is the largest insurance company in Italy and arguably one of the biggest in Europe", done: true },

  ];
  return {
    all: function() {
      return cardTypes;
    }
  }

});

$ http callback

.factory('Cards', function($http) {
    var cardTypes = {};

    $http.post("http://url", {
        "auth": "cats",
        "name": "Adam",
        "uuid": "fasfA"
    }).
    success(function(data, status, headers, config) {
        cardTypes = data;
    }).
    error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
    });

    return {
        all: function() {
            return cardTypes;
        }
    }
});

1 个答案:

答案 0 :(得分:0)

请记住.http()是异步调用。因此,在初始化工厂之后直接调用.all()将导致返回一个空对象,因为在调用.all()时,post请求可能仍然未决。

我建议使用服务(也可以使用工厂,但是这里的服务更合适)并返回承诺:

this.getAll = function() {
    return $http.post("http://url",{"auth":"cats","name":"Adam","uuid": "fasfA" });
}

然后在你的控制器中你可以这样做:

Cards.getAll().then(function(c){
     $scope.cards = c;
})