简体   繁体   中英

Is it possible for ngResource to be called synchronously?

I currently have a factory which I'm using to retrieve a config file.

  m.factory('clientConfig', function($resource) {
    var r;
    r = $resource('assets/config.json', {}, {
      query: {
        method: 'GET'
      },
      isArray: false
    });
    return r.query();
  });

The config file is a json file which contains the location of a nodeJS server. In my local environment, the json file is

{
    "serverURL": "http://localhost\\:3000"
}

When I start my app on the front page this is fine. The front page loads the clientConfig module, and any subsequent page just uses the clientConfig module like below without any problem

m.factory('House', function($resource, clientConfig) {
    return $resource(clientConfig.serverURL + '/houses/:houseId',
...

The problem I'm running into is if I enter the site on a page that immediately wants to load data from the server. In that case, because clientConfig is not populated yet and still empty and this stuffs up my $resource(clientConfig.serverURL + '/houses/:houseId' call.

My question is is it possible to load up clientConfig synchronous or at least have my app not start until after clientConfig has been populated?

You can't. $resource always returns asynchronous data. If you want synchronous data then use $http instead of $resource.

Change your service like this;

         m.factory('clientConfig', function($http) {
        var get = function {
        $http.get('assets/config.json').success(function(data)){
                return data.serverURL;
});
    };

        });

And call the service like;

clientConfig.get();

You can't. Since JavaScript is (mostly) single threaded, there are very very few blocking operations. XHR is not one of those. There is no way to make it synchronous.

Depending on your angular version, you can either $then or $promise it:

clientConfig.$then(function (){ do something})

or

clientConfig.$promise.then(function () {do something else})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM