0

My angular app has some resources that I need to initialise with a string, e.g:

angular.module('client.core.resources')
   .factory('AuthenticationResource', ['$resource','ConstantValueService', function ($resource,ConstantValueService) {
  var authUrl = ConstantValueService.get('webApiUri') + '/api/authentication';
  return $resource(authUrl, {},
      {
        login: {
          method: 'POST',
          isArray: false
        },
        logout: {
          method: 'DELETE',
          isArray: false
        }
      });
}]);

Now I have some data in an external json file that contain values for a webApiUri. I tried to do the following:

 angular.module('myapp').run(['$http',function($http){
      $http.get('client.json').success(function (settings) {
        ConstantValueService.setFields(settings);
    });
  }])

However, as it is an async process, tracing shows that in the above mentioned resource, authUrl gets initialised way before client.json is loaded. So in resource the authUrl = undefined.

I would like to know if there is a nice way to postpone initialising and running of the angular app until the $http promise is fulfilled.

Gurfuffle
  • 784
  • 12
  • 32
onkami
  • 8,791
  • 17
  • 90
  • 176
  • I'm not familiar enough with angular to give a full solution but your first code has a dependency on `ConstantValueService`. Make sure angular knows that it's a dependency and when it's _ready_ to be used (after `.setFields`) – Halcyon Aug 11 '14 at 13:57
  • 3
    Have you tried loading the client.json file with a script tag? If the data is static and sitting in that file, you can load it as a script. – Surreal Dreams Aug 11 '14 at 13:58
  • You could also use jQuery to load the data synchronously. – Dreamwalker Aug 11 '14 at 14:04

1 Answers1

0

There is an excellent summary of this topic in this other StackOverflow Question.

I made my own demo based on your particular problem, see the project in GitHub. I based my solution to the proposal by JBCP, i.e., the manual initialization, as I thought that was closest to the spirit of your case.

Please read also what the official documentation says about this.

Community
  • 1
  • 1
masa
  • 2,762
  • 3
  • 21
  • 32