【发布时间】:2015-06-22 08:59:15
【问题描述】:
我有奇怪的 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);
有人知道将数据保存在变量中(为其他控制器兑现)并在屏幕上显示数据的更好方法吗?我想尽可能多地跳过样板代码:)。
【问题讨论】:
标签: json angularjs web-services rest