繁体   English   中英

angularjs从属性文件中读取

[英]angularjs read from properties file

在angularJS中,如何从属性文件中读取值?

connection.properties:  

url="http://localhost:8080"  
user= "me"  
get= "GET"  
post= "POST"

app.js:

var app = angular.module('testing',[]);  
app.controller('testCtrl',function($scope,$http) {    
     $http({    
        url: connection.properties.url  ,
        method: connection.properties.get,  
        params: {user: connection.properties.user})        
     });
});

如果connection.properties是Web服务器上的文件,那么您只需执行以下操作:

var app = angular.module('app', []);

app.controller('test', function ($scope, $http) {
  $http.get('connection.properties').then(function (response) {
    console.log('a is ', response.data.a);
    console.log('b is ', response.data.b);
  });
});

你可以在这里看到一个例子:

http://plnkr.co/edit/3Ne3roFOwcfVmg2mgnUr?p=preview

简单的方法是

  1. 创建一个名为的js文件

    “config.js”(假设在路径scripts / config / config.js中)

    config.js:

    var test1 =“http://testurl.com”var test2 =“globalconstant”

  2. 在html页面中,在顶部包含此config.js(在主controller.js上方): **<script.. src="./scripts/config/config.js"></st>**

  3. 在控制器中进行以下更改:

    MainController.js:$ scope.appUrl = test1; $ scope.appConstant = test2;

兰登的回答为我加载了属性文件的内容,但是我无法以response.data.aresponse.data.b等格式访问属性中的值,并且始终返回undefined 对于我可以使用的值,我必须提取属性文件的内容并将其转换为JSON格式,然后才能使用它。 对上述解决方案的修改将是这样的:

var app = angular.module('app', []);

app.controller('test', function ($scope, $http) {
    function extractProperties(data){
        const lines = data.split("\n");
        properties = {}

        for (const l of lines) {
            const line = l.trim();
            if (!line || line[0] === '#') {
                continue;
            }
            const keyValue = line.split("=");
            const key = keyValue[0].trim();
            const value = keyValue[1].trim();
            properties[key] = value

        }

        return properties;
    }

    $http.get('connection.properties').then(function (response) {
        const properties = extractProperties(response.data);
        console.log('URL is ', properties.url);
        console.log('User is ', properties.user);
    });
});

暂无
暂无

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

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