无法使用angularjs $ http.get

时间:2015-06-22 08:59:15

标签: json angularjs web-services rest

我有奇怪的angularjs问题。我正在尝试从Rest Webservice获取数据。它工作正常,但我无法将json数据保存到对象。我的代码如下:

services.service('customerService', [ '$http',  '$cacheFactory', function($http, $cacheFactory) {
var cache = $cacheFactory('dataCache');
var result = cache.get('user');
this.getById = function(id){
    $http.get(urlList.getCustomer + id).success(function(data, status, headers, config) {
        result = data;
        cache.put('user', result);
        console.log(data);
    }).error(function(data, status, headers, config) {
        //
    });
    return cache.get('user');
};
}]);


services.service('customerService', [ '$http', function($http) {
var result;
this.getById = function(id){
    $http.get(urlList.getCustomer + id).success(function(data, status, headers, config) {
        result = data;
        console.log(data);
    }).error(function(data, status, headers, config) {
        //
    });
    return result;
};
}]);

两种方法都不起作用。我错过了什么吗?

PS:“console.log”方法成功打印json数据。

编辑:

经过一些编辑,我得出了类似的东西:

services.service('customerService', [ '$http', function($http) {
var result;
this.getById = function(scope, id){
    $http.get(urlList.getCustomer + id).success(function(data, status, headers, config) {
        result = data;
        console.log(data);
        scope.userData = data;
    }).error(function(data, status, headers, config) {
        //
    });
    return result;
};
}]);
控制器中的

customerService.getById($scope, id);

任何人都知道更好的方法来保存变量中的数据(为其他控制器兑现)并在屏幕上显示数据?我想跳尽可能多的样板代码:)。

2 个答案:

答案 0 :(得分:3)

cache.get是异步的。执行return result// Some View <div>{{myData}}</div> // Controller app.controller('MyController', function ($scope, $http) { $http.get('yoururl').success(function (data) { $scope.myData = data; }); }); 时,HTTP请求尚未完成。你打算如何使用这些数据?在UI中显示?例如。尝试以下方法:

// in your service
this.getById = function(id){
  return $http.get(urlList.getCustomer + id).success(function (data) {
    return data;
  });
}

// in directive/controller
customerService.getById(someId).then(function (customer) {
  $scope.customerId = customer.id;
});

你明白了吗?

查看承诺的使用方式。从您的服务函数,您可以返回$ http.get返回的承诺,您可以在控制器/指令中使用它,如下所示:

jQuery.validator.addMethod("datesanity", function(value, element) {
    return this.optional(element) || function(){
        var myDate = value.split('/');
        var subDay = myDate[0];
        var subMonth = myDate[1]-1;
        var subYear = myDate[2];
        // this will "correct" any out of range input
        var subDate = new Date(subYear, subMonth, subDay);
        var calcDay = subDate.getDate();
        var calcMonth = subDate.getMonth();
        var calcYear = subDate.getFullYear();
        // this checks to see if any of the submitted input was out of range
        // comment this out to ignore the discrepancy if you want to set a "corrected" value below
        if (calcDay == subDay && calcMonth == subMonth && calcYear == subYear) {
            return true;
            }
        else {
            return false;
        }
    };
});

答案 1 :(得分:0)

这就是你的方法应该是这样的,success是一个异步的承诺,这意味着你在return result;被触发之前调用了success

return {      
        getById : function(id){
            return $http.get(urlList.getCustomer + id).success(function(data, status, headers, config) {
                return data;
            }).error(function(data, status, headers, config) {
                //
            });
        };
}