如何从$ HTTP调用设置变量,然后用它在应用程序的其它部分没有使整个应用程序异步 [英] How to set a variable from an $http call then use it in the rest of the application WITHOUT making the whole application asynchronous

查看:134
本文介绍了如何从$ HTTP调用设置变量,然后用它在应用程序的其它部分没有使整个应用程序异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据。

{
  "config": {
    "RESTAPIURL": "http://myserver/myrestsite"
  }
}

和我有这个工厂读取数据

and I have this factory that reads that data

'use strict';

angular.module('myApp').factory('api',
  ["$http", "$q",
  function ($http, $q) {

    function _getConfiguration() {
      var deferred = $q.defer();
      $http.get('/scripts/constants/config.json')
      .success(function (data) {
        deferred.resolve(data);
      })
      .error(function (data, status) {
        deferred.reject(data, status);
      });
      return deferred.promise;
    }

    function _restApiUrl() {
      // this doesn't work either. _getConfiguration() doesn't resolve here.
      return _getConfiguration().RESTAPIURL + '/api/';
    }

    return {
      URL: _restApiUrl
    }
  }
  ]
);

然后用它

'use strict';

angular.module('myApp').factory('AuthService', function ($http, $q, api,NotificationService) {

    function _get(creds) {

        var deferred = $q.defer();

        $http({method: 'GET', url: api.URL() + api.AUTH, headers: {
            'Authorization': 'Basic '+creds}
        })
        .success(function (data, status, results, headers) {
            deferred.resolve(results);
        })
        .error(function (data, status) {
            NotificationService.redirect(status);
            deferred.reject(data, status);
        });
        return deferred.promise;
    }

    return {
        get:_get
    };
});

所以,当我使用它,我在做 api.URL()键,它不工作。

它曾经是硬codeD URL所以它使用的是 api.URL 打电话。我真的不想去通过整个应用程序,并转换一切 api.URL()。然后,(...)。这将吸。

It used to be hard coded URL so to call it used to be api.URL. I really don't want to go through the whole app and convert everything to api.URL().then(...). That would suck.

所以,我怎么能这个值敲定为财产,而不是一个必须一遍又一遍地叫异步承诺?

So how can I nail down this value as a "property" instead of an asynchronous promise that has to be called over and over?

通话一次,罚款。获得的价值。把它放在什么地方。使用的值。永远不要叫 $ HTTP 再后。

Call it once, fine. Get the value. Put it somewhere. Use the value. Don't ever call the $http again after that.

修改

这是转向了是我曾经问最成功的问题之一,而我感激地通过依次每个答案去。感谢你们每一个人。

This is turning up to be one of the most successful questions I've ever asked, and I am gratefully going through each answer in turn. Thank each one of you.

推荐答案

定义何时加一点什么@ThinkingMedia是说在注释,用 UI路由器控制器你可以添加一个决心参数。

Adding a bit to what @ThinkingMedia was saying in the comment, with ui-router when defining controllers you can add a resolve parameter.

在这你可以指定一些承诺的带有,以解决控制器进行实例化之前,因此你总是确保配置对象是提供给控制器或其他服务,该控制器使用。

In it you can specify some promises that have to resolve before the controller is instantiated, thus you are always sure that the config object is available to the controller or other services that the controller is using.

您也可以在 UI路由器父/子控制器,所以你可以有一个 RootController 能解决配置对象和所有其他控制器从RootController继承

You can also have parent/child controllers in ui-router so you could have a RootController that resolves the config object and all other controllers inheriting from RootController

.state('root', {
    abstract: true,
    template: '<ui-view></ui-view>',
    controller: 'RootController',
    resolve:{
      config: ['api', function(api){
        return api.initialize();
      }       
    }
  });

和你的API工厂:

angular.module('myApp').factory('api',
  ["$http", "$q",
  function ($http, $q) {
    var _configObject = null;

    function initialize() {
      return $http.get('/scripts/constants/config.json')
      .then(function (data) {
          _configObject = data;
          return data;
      });
    }

    // you can call this in other services to get the config object. No need to initialize again
    function getConfig() {
      return _configObject;
    }

    return {
      initialize: initialize,
      getConfig: getConfig
    }
  }
  ]
);

这篇关于如何从$ HTTP调用设置变量,然后用它在应用程序的其它部分没有使整个应用程序异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆