简体   繁体   English

是否可以同步调用ngResource?

[英]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. 配置文件是一个json文件,其中包含nodeJS服务器的位置。 In my local environment, the json file is 在我的本地环境中,json文件是

{
    "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 首页加载clientConfig模块,任何后续页面只是使用如下所示的clientConfig模块而没有任何问题

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. 在这种情况下,因为clientConfig尚未填充且仍然为空,这会占用我的$ resource(clientConfig.serverURL +'/ houses /:houseId'调用。

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? 我的问题是是否可以加载clientConfig同步或至少让我的应用程序在clientConfig填充之后才开始?

You can't. 你不能。 $resource always returns asynchronous data. $ resource总是返回异步数据。 If you want synchronous data then use $http instead of $resource. 如果你想要同步数据,那么使用$ http而不是$ 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. 由于JavaScript(大部分)是单线程的,因此阻塞操作非常少。 XHR is not one of those. XHR不是其中之一。 There is no way to make it synchronous. 没有办法让它同步。

Depending on your angular version, you can either $then or $promise it: 根据你的角度版本,你可以$ then或$承诺:

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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