-1
(function () {
angular.module("app").controller('DashboardController', ['$q', 'dashboardService', function ($scope, $q,dashboardService) {
    var DashboardController = this;
    dashboardService.loadFromServer(DashboardController );
    console.log("DashboardController ", DashboardController);
}])
})();


angular.module("app").service('dashboardService', ['$http', '$q', function ($http, $q) {
return {
    loadFromServer: function (controller) {
        var getDashboardEntries = $http.get('http://someUrl');
        var getEmailData = $http.get('http://someOtherUrl');
        var getSidebarData = $http.get('http://yetAnotherUrl');

        return $q.all([getDashboardEntries, getSidebarData, getEmailData])
          .then(function (results) {
              controller.dashboardData = results[0].data;
              controller.chartData = results[1].data;
              controller.emailData = results[2].data;
          });
    },
};
}]);

1.The service returns the three bits of data and this is the results when logged using:

console.log("DashboardController ", DashboardController);

enter image description here

  1. When I try to drill down on the data in this manner it logs "undefined"

    console.log("DashboardController "DashboardController.dashboardData); console.log("DashboardController "DashboardController.chartData); console.log("DashboardController "DashboardController.emailData);

Tomc-s
  • 33
  • 5

1 Answers1

1

Do you realize that console.log is executed right after invoking loadFromServer before the server has chance to respond and promise resolves? The actual order is:

  1. loadFromServer
  2. console.log
  3. promise success method - where you actually have your data

Change your controller's code to this:

dashboardService.loadFromServer(DashboardController ).then(function() {
    console.log("DashboardController ", DashboardController);
});

What would be even better is to construct some object from parts of responses and assign it in the controller itself - not the service. In current implementation if you wanted to have another controller then service would assign response parts to same fields. I'd propose sth like this:

return $q.all([getDashboardEntries, getSidebarData, getEmailData])
      .then(function (results) {
          var data = {
              dashboardData = results[0].data;
              chartData = results[1].data;
              emailData = results[2].data;
          };

          return data;
      });

and then in controller:

dashboardService.loadFromServer().then(function(data) {
    DashboardController.dashboardData = data.dashboardData;
    DashboardController.chartData = data.chartData;
    DashboardController.emailData = data.emailData;
});

In this solution the controller decides what to do with data, not the other way around.

Keammoort
  • 3,075
  • 15
  • 20