如何从 angular 中的服务获取数据结果
How to get data result from service in angular
我必须获取来自 API 的数据,在本例中我使用了一个控制器和一个服务,它是服务 `daryo.factory('daryoSvc', ['$http ', 函数 ($http) {
var categories = [];
var categoriesjon = function () {
$http.get('http://localhost:18737/Category/GetCategories').
success(function (data, status, headers, config) {
categories = {
"one": "two",
"key": "value"
};
alert('g');
})
.error(function (data, status, headers, config) {
console.error(data);
});
return categories;
}
var factoryService = {
categories: categoriesjon
};
return factoryService;
}]);`
这是我的控制器函数`daryo.controller('daryoCtrl', ['$scope', 'daryoSvc', function ($scope, daryoSvc) {
var self = $scope;
self.categories = daryoSvc.categories;
console.log(daryoSvc.categories);
}]);`
它不能正常工作,因为我没有使用 $q promise 选项而且我没有找到好的解决方案,我该如何解决?谢谢!
您的服务 returns 一个空数组。一旦异步 http 调用成功,这个空数组就会被一个新数组替换,但是使用这个服务的控制器仍然有一个对旧的空数组的引用。另一个问题是控制器甚至不调用服务。它所做的只是在范围内存储对服务函数的引用。
代码应该是
var categoriesjon = function () {
// executed at t1
return $http.get('http://localhost:18737/Category/GetCategories').
then(function (response) {
// executed at t2, long after t1
var categories = {
"one": "two",
"key": "value"
};
return categories;
})
.catch(function (response) {
console.error(response.data);
});
};
在控制器中:
// executed at t0
daryoSvc.categories().then(function(data) {
// executed at t3
$scope.categories = data;
});
我必须获取来自 API 的数据,在本例中我使用了一个控制器和一个服务,它是服务 `daryo.factory('daryoSvc', ['$http ', 函数 ($http) {
var categories = [];
var categoriesjon = function () {
$http.get('http://localhost:18737/Category/GetCategories').
success(function (data, status, headers, config) {
categories = {
"one": "two",
"key": "value"
};
alert('g');
})
.error(function (data, status, headers, config) {
console.error(data);
});
return categories;
}
var factoryService = {
categories: categoriesjon
};
return factoryService;
}]);`
这是我的控制器函数`daryo.controller('daryoCtrl', ['$scope', 'daryoSvc', function ($scope, daryoSvc) {
var self = $scope;
self.categories = daryoSvc.categories;
console.log(daryoSvc.categories);
}]);`
它不能正常工作,因为我没有使用 $q promise 选项而且我没有找到好的解决方案,我该如何解决?谢谢!
您的服务 returns 一个空数组。一旦异步 http 调用成功,这个空数组就会被一个新数组替换,但是使用这个服务的控制器仍然有一个对旧的空数组的引用。另一个问题是控制器甚至不调用服务。它所做的只是在范围内存储对服务函数的引用。
代码应该是
var categoriesjon = function () {
// executed at t1
return $http.get('http://localhost:18737/Category/GetCategories').
then(function (response) {
// executed at t2, long after t1
var categories = {
"one": "two",
"key": "value"
};
return categories;
})
.catch(function (response) {
console.error(response.data);
});
};
在控制器中:
// executed at t0
daryoSvc.categories().then(function(data) {
// executed at t3
$scope.categories = data;
});