lundi 7 décembre 2015

Async data retrievel in angularjs

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!

Aucun commentaire:

Enregistrer un commentaire