B
B
Boogie19892016-07-26 10:32:44
JavaScript
Boogie1989, 2016-07-26 10:32:44

How to pass data after request from service to controller?

At the moment I have a page at the entrance to which about 10 requests are sent from the controller to get information. This option is no good anywhere, since at each re-entry, infa is requested anew. Decided to remake everything in the service. It turned out something like this:

.factory('Widget1DataService', Widget1DataService);

    /** @ngInject */
    function Widget1DataService(TodayTabService, $q) {
        var widget1 = {};
        widget1.setData = function(data) {
            if (!widget1.data) {
               widget1.data={};
                $q.all([
                    $http.post("/products/count/today", date),
                    $http.post("/out/today", date)
                ]).then(function(response) {
                    widget1.data1 = response[0];
                    widget1.data2 = response[1]
               });
            }
        }
        return widget1;
    }

In the controller I define variables :
var vm=this;
vm.data1 = Widget1DataService.data1.count;
vm.data2= Widget1DataService.data2.count.today;

But the problem is that there is neither Widget1DataService.data1.count nor Widget1DataService.data2.count.today at this moment, since they have not arrived yet. How to do it all right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2016-07-26
@Boogie1989

function Widget1DataService($q, $http) {
  var dataPromise;
  this.getData = getData;

  function getData(date) {
    if (dataPromise) return dataPromise;
    dataPromise = $q.all([
                    $http.post("/products/count/today", date),
                    $http.post("/out/today", date)
                ]).then(function(response) {
                    return {
                      data1: response[0],
                      data2: response[1]
                    };
               });
    return dataPromise;
  }  
}

Widget1DataService.getData(...)
  .then(function(data) {
    $scope.widgetData = data;
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question