0

I have an async problem in my angularjs app.

What I want to do is to retrieve the data from remote server (in prefsService.js). And then assign the values of data to variables in controller(in prefsController.js).

Here is the prefsService.js file:

 (function() {
  'use strict';

  angular
    .module('app')
    .factory('PrefsService', PrefsService);

  PrefsService.$inject = ['$resource','PrefsResource'];

  function PrefsService($resource,PrefsResource) {

    var initialize = function() {
      var twentyFourHourTime = null;
      var decimalTime = null;
      var startDayOfWeek = null;
      var roundingOption = null;
      var roundingIncrement = null;

      PrefsResource.get({key:"TwentyFourHourTime"}, function(data) {
        if (data.result.value === null||undefined) {
            twentyFourHourTime = 0;
        } else {
            twentyFourHourTime = data.result.value;
        }
            PrefsResource.get({key:"DecimalTime"}, function(data) {
              if (data.result.value === null||undefined) {
                  decimalTime = 0;
              } else {
                  decimalTime = data.result.value;
              }
                  PrefsResource.get({key:"startDayOfWeek"}, function(data) {
                    if (data.result.value === null||undefined) {
                        startDayOfWeek = 0;
                    } else {
                        startDayOfWeek = data.result.value;
                    }

                    return {"twentyFourHourTime":twentyFourHourTime,"decimalTime":decimalTime,"startDayOfWeek":startDayOfWeek}
              });
            });
      });


    };

    return {
      initialize: initialize
    };

  }

})();

Here is the prefsController.js file:

vm.test=PrefsService.initialize();
console.log('Prefs data initialized', vm.test);

When I run it, vm.test always is "undefined".

What should I do? Thx!

Bluesea
  • 135
  • 1
  • 1
  • 9
  • Why are you making your AJAX calls serially when they don't depend on each other? – Adam Jenkins Dec 07 '15 at 17:01
  • And why do you do them in the factory? In the factory you define the resource to be used in the controller to get/query/post/put/etc... – michelem Dec 07 '15 at 17:08
  • Hi, I am a new programmer...I want do this in factory because I want use this functionality in multiple controllers... – Bluesea Dec 07 '15 at 19:10

1 Answers1

2

I haven't syntax-checked this, but the gist of it, as with all asynchronous programming is promises. This question is a dupe (who can ever find the master dupe of this type of question anymore?) but here's how to do it using angular:

 (function() {
  'use strict';

  angular
    .module('app')
    .factory('PrefsService', PrefsService);

  PrefsService.$inject = ['$resource','PrefsResource'];

  function PrefsService($resource,PrefsResource) {

    var initialize = function() {

      //return a promise
      return $q
        .all([
          PrefsResource.get({key:"TwentyFourHourTime"}),
          PrefsResource.get({key:"DecimalTime"}),
          PrefsResource.get({key:"startDayOfWeek"})
        ])
        .then(function(values) {
          var 
            twentyFourHourTime = values[0],
            decimalTime = values[1],
            startDayOfWeek = values[2];

          //return the value (object) when all promises have resolved
          return {
            "twentyFourHourTime":twentyFourHourTime.result.value || 0,
            "decimalTime":decimalTime.result.value || 0,
            "startDayOfWeek":startDayOfWeek.result.value || 0
          }
        })
    }


    return {
      initialize: initialize
    };

  }

})();


PrefsService
  .initialize()
  //use the promise API to log messages only after the promise has resolved
  .then(function(prefs) {
    console.log('initialized');
    console.log(prefs);
  })
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • Thx. But it seems that only the value of "TwentyFourHourTime" can be retrieved. In other words, the "values" variable only contains an object of "TwentyFourHourTime" – Bluesea Dec 08 '15 at 16:37
  • It returns {"values":{"$resolved":false,"$promise":{"status":"ok","result":{"key":"TwentyFourHourTime","value":null}}}} – Bluesea Dec 08 '15 at 16:49
  • My fault, `$q.all` takes an array, or an object. not multiple parameters. I've edited the answer. – Adam Jenkins Dec 08 '15 at 17:07
  • It works perfect now. I am very new to angularjs and web development. Thank you very much! – Bluesea Dec 09 '15 at 14:58
  • a quick question: there is a json object :test={"status":"ok","result":{"key":"TwentyFourHourTime","value":"24"}} I want to use test.result to read the inner object. But it always gives me 'undefiend'. What the problem could be? Thx – Bluesea Dec 09 '15 at 15:57
  • @Bluesea - is it an actual object? if you have this in the code: `test={"status":"ok","result":{"key":"TwentyFourHourTime","value":"24"}}` then you've got a string, not an object. – Adam Jenkins Dec 09 '15 at 16:06
  • I have added a picture of that json object in my question. – Bluesea Dec 09 '15 at 16:17
  • If you have time, please see this link...http://stackoverflow.com/questions/34183991/how-to-retrieve-the-key-value-object-in-json-with-javascript – Bluesea Dec 09 '15 at 16:50