S
S
Stepan Kormilin2015-12-14 00:32:12
Angular
Stepan Kormilin, 2015-12-14 00:32:12

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

3 answer(s)
N
Nick Nesterov, 2015-12-14
@Stepan13

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();
}]);

Or we can use this data in another controller:
angular.module('myApp').controller('mainPageCtrl', ['$scope', 'dataService', function($scope, dataService){
         $scope.dataForMainView = dataService.getData();
}]);

And our service:
angular.module('eventsideApp').factory('dataService', function(){
  var dataCtrl = {};
  
  return {
    setData: function (data) {
      dataCtrl = data;
      return dataCtrl;
    },
    getData: function () {
      return dataCtrl;
    }
  };
});

N
Nicholas, 2015-12-14
@healqq

$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);
});

M
Mikhail Osher, 2015-12-14
@miraage

// 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 question

Ask a Question

731 491 924 answers to any question