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!

3
  • Why are you making your AJAX calls serially when they don't depend on each other? Commented Dec 7, 2015 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... Commented Dec 7, 2015 at 17:08
  • Hi, I am a new programmer...I want do this in factory because I want use this functionality in multiple controllers... Commented Dec 7, 2015 at 19:10

1 Answer 1

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);
  })
Sign up to request clarification or add additional context in comments.

8 Comments

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"
It returns {"values":{"$resolved":false,"$promise":{"status":"ok","result":{"key":"TwentyFourHourTime","value":null}}}}
My fault, $q.all takes an array, or an object. not multiple parameters. I've edited the answer.
It works perfect now. I am very new to angularjs and web development. Thank you very much!
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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.