【问题标题】:Reading properties file value in Angular在Angular中读取属性文件值
【发布时间】:2015-12-30 21:49:00
【问题描述】:

我已经看过一些关于使用$http 服务访问属性文件的回复,但现在确定它如何适合这种情况 我创建了一个从 poperties 文件返回主机名的服务,调用此服务的客户端应该对服务进行阻塞调用,并且只有在读取属性文件时才继续。

var serviceMod = angular.module('serviceModule',[])
.factory('configService', function($http){
    return {
        getValue: function(key){
            $http.get("js/resources/urls.properties").success(function(response){

                console.log('how to send this response to clients sync??? ' + response)

            })
            return ????

        }
    }
})

someOtherControllr.js

var urlValue = configService.getValue('url')

我面临的问题与$http 服务的异步特性有关。当回调收到响应时,主线程已经执行完someOtherController.js

【问题讨论】:

  • 我的建议对您有帮助吗?请分享您的发现

标签: javascript angularjs angularjs-service


【解决方案1】:

您需要解决服务返回的承诺。我们可以只返回 $http 调用并在我们的控制器中解决它(因为 return $http.get 本身就是一个承诺)。查看 AngularJS $q 和 $http 文档以更好地理解正在发生的底层机制,并观察以下变化...

.factory('configService', function($http) {
    return {
        getValue: function(key) {
            return $http.get('js/resources/urls.properties');
        }
    }
});

var urlValue;

// --asynchronous
configService.getValue('url').then(function(response) {
    urlValue = response.data; // -- success logic
});

console.log('be mindful - I will execute before you get a response');
[...]

【讨论】:

  • 所以每次我们需要访问调用userController.js中的url时,都要在响应块中写客户端代码?
  • 嗯,这只是静态数据吗?为什么不创建一个constant 或将其放在您的应用程序.run 块中的$rootScope 上?您能否详细解释一下您需要此功能的用途、频率以及是否会发生变化?
  • 另外,你是不是偶然使用了ui-router?
  • 它不能是常数,因为我不应该触摸或修改 js 文件,因为这些值可能会被其他非技术人员更改。
  • 那么这应该可以。您的具体担忧是什么?也不需要进行这种同步,这通常不是一个好主意。在这种情况下,什么不适用于异步?
【解决方案2】:

简单的方法 - 使用回调(它仍然是异步的。事实上你不能让它同步):

    getValue: function(key, onSuccess){
        $http.get("js/resources/urls.properties").success(function(response){
            onSuccess(response);
   })

【讨论】:

    猜你喜欢
    • 2015-11-10
    • 1970-01-01
    • 2017-07-20
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 2013-05-26
    相关资源
    最近更新 更多