#angularjs #ionic-framework
#angularjs #ionic-framework
Вопрос:
У меня есть служебная функция, как показано ниже
.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;
});
Как мне это сделать?
Ответ №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. Я хочу, чтобы мой сервис был точно таким
2. Но я хочу заменить только элементы
3. Я не понимаю
Ответ №2:
.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;
}
};
}]);