Answer the question
In order to leave comments, you need to log in
How to store the result (data) of $http.get request for later use?
Good afternoon!
I make a request and try to somehow save the result in order to use this data one more time in the future without making a second request. As a normal object from the controller to the service - it doesn't work.
Answer the question
In order to leave comments, you need to log in
Everything depends on the specific case. If you want to use the same data in the same controller, then you do not need to take it out to the service. But if they are also used in others, then they need to be taken out.
Controller:
angular.module('myApp').controller('homePageCtrl', ['$scope', 'dataService', function($scope, dataService){
$http.get('/data').success(function(data){
$scope.dataForView = data;
dataService.setData(data);
});
//можем и в данном контроллере использовать повторный раз данные
$scope.dataForView = dataService.getData();
}]);
angular.module('myApp').controller('mainPageCtrl', ['$scope', 'dataService', function($scope, dataService){
$scope.dataForMainView = dataService.getData();
}]);
angular.module('eventsideApp').factory('dataService', function(){
var dataCtrl = {};
return {
setData: function (data) {
dataCtrl = data;
return dataCtrl;
},
getData: function () {
return dataCtrl;
}
};
});
$http service returns a Promise object.
To interact with it, the Promises API is used :
$http.get('/somepath')
.then(function(data) {
// обрабатываем полученный ответ от сервера
// объект data можно присвоить чему угодно, тут отличий никаких нет
console.log(data);
},
function(error) {
// сюда мы попадаем, если при обрабоке запроса произошла ошибка
console.log(error);
});
// somectrl.js
function SomeCtrl(SomeService) {
var vm = this;
SomeService.getData().then(function (data) {
vm.data = data;
});
}
// someservice.js
function SomeService($http) {
this.getData = function () {
// Если данные всегда одинаковые - можно написать вторым параметром {cache: true}
return $http.get('/data').then(fetchResponse, fetchResponse);
function fetchResponse(response) {
return response.data;
}
};
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question