我有一个服务功能如下所示
.service('ItemService', ['$http', function ($http) {
var items = [{'item_id': '1', 'item_name': 'abc'}];
return {
getItems: function () {
return items;
},
setItems: function (value) {
items = value;
}
};
}]);
此代码工作正常,我想让项目动态,例如
var items = $http({
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
method: 'POST',
url: 'http://localhost/app/item/get/10',
}).then(function (response) {
return response.data;
});
我该怎么做?
答案 0 :(得分:1)
您的服务将是这样的
.service('ItemService', ['$http', function($http) {
return {
getItems: function(id) {
return $http({
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'GET',
url: 'http://localhost/app/item/get/' + id,
})
},
setItems: function(items) {
return $http({
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST',
url: 'http://localhost/app/item/' + items,
})
}
};
}]);
你应该像你这样在你的控制器里面调用它
ItemService.getItems().then(function(response){
//Retrieve the data
$scope.items = response.items;
}, function(error){
//Handle the errors
})
答案 1 :(得分:0)
.service('ItemService', ['$http', function ($http) {
// I want to initialize this items array before I call getItems funtion, Anyway to do the same?
var items = [{'item_id': '1', 'item_name': 'abc'}];
//Below section I want exactly same I will change items array from my controller and also I will use getItem again to get this items array agian. My getItems should only return the items array
return {
getItems: function () {
return items;
},
setItems: function (value) {
items = value;
}
};
}]);