Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing AngularJS service factory style

I have a service that retrieves data via REST. I want to store the resulting data in service level variable for use in multiple controllers. When I put all the REST logic directly into controllers everything works fine but when I attempt to move the retrieval / storing of data into a service the controller is not being updated when the data comes back. I've tried lots of different ways of maintain the binding between service and controller.

Controller:

myApp.controller('SiteConfigCtrl', ['$scope', '$rootScope', '$route',  'SiteConfigService',
function ($scope, $rootScope, $route, SiteConfigService) {

    $scope.init = function() {
        console.log("SiteConfigCtrl init");
        $scope.site = SiteConfigService.getConfig();
    }

}

]);

Service:

 myApp.factory('SiteConfigService', ['$http', '$rootScope', '$timeout', 'RESTService',
 function ($http, $rootScope, $timeout, RESTService) {

    var siteConfig = {} ;

    RESTService.get("https://domain/incentiveconfig", function(data) {
        siteConfig = data;
    });

    return {

        getConfig:function () {
            console.debug("SiteConfigService getConfig:");
            console.debug(siteConfig);

            return siteConfig;
        }

     };
 }
]);

View:

<div class="span4" ng-controller="SiteConfigCtrl">
            <header>
                <h2>
                    {{site.title}}
                </h2>
            </header>
like image 442
wisemanIV Avatar asked Mar 22 '23 21:03

wisemanIV


1 Answers

I would write it with promise factory:

myApp.factory('SiteConfigService', ['$http', '$rootScope', '$timeout', 'RESTService', '$q'
 function ($http, $rootScope, $timeout, RESTService, $q) {

    var siteConfig = {} ;

    RESTService.get("https://domain/incentiveconfig", function(data) {
        siteConfig = data;
    });

  // or just 
  // var siteConfig = RESTService.get("https://domain/incentiveconfig");

    return {

        getConfig:function () {
             var deferred = $q.defer();
             deferred.resolve(siteConfig);

              return deferred.promise;    
        }

     };
 }
]);

Controller side

         SiteConfigService.getConfig()
                    .then(function (result) {
                       $scope.site = result;                           
                    }, function (result) {
                        alert("Error: No data returned");
                    });
like image 162
Maxim Shoustin Avatar answered Apr 01 '23 07:04

Maxim Shoustin