简体   繁体   中英

How to read Java property file in AngularJS?

Is there any way to read a properties file from angularjs which resides outside the web server?

like in java the property file deployed out of the project but we can read those file in our project as filter.properties in this way any solution is there in angularJS.

I tried like this but getting undefined.

filter.properties:

key1=value1 
key2=value2

sampleController.js

var app = angular.module('sampleApp', []);
    app.controller('sampleController', function($scope, $http) {
    $http.get('filter.properties').then(function (response) {
        console.log('a is ', JSON.stringify(response.data.key1));
    });
});

There are several ways to access properties files in angularjs.

Like every files properties file is a file with .properties extension. Since java properties files are key value pair separated by = in a single line.

So we can convert a properties file into javascript object by iterating each lines in properties file and split-ing it with = symbol and storing it as javascript object which will help to access it quickly.

Here is its javascript implementation

function extractProperties(propertiesFileContents){
  var keyValuePairs =propertiesFileContents.split("\n");
  properties ={}
  for (i = 0; i < keyValuePairs.length; i++) {
     var keyValueArr=keyValuePairs[i].trim().split("=");
     var key=keyValueArr[0];
     var value=keyValueArr[1];
     properties[key]=value
  }
  return properties;
}

Based on your code here iam adding a plunker here hope this may help you

Samuel J Mathew's solution works for me, but the properties file I have to deal with have multiple empty lines in the file, together with lines commented out, and sometimes with white spaces around the = sign. So I have to add some checks to handle these situations. The modified result is such, hopefully will be useful to those working with a more complex properties file:

function extractProperties(data){
    const keyValuePairs = data.split("\n");
    properties = {}

    for (var i = 0; i < keyValuePairs.length; i++) {
      const keyValuePair = keyValuePairs[i].trim();
      if (!keyValuePair || keyValuePair[0] === '#') {
        continue;
      }
      const keyValueArr = keyValuePair.split("=");
      const key = keyValueArr[0].trim();
      const value = keyValueArr[1].trim();
      properties[key] = value
    }

    return properties;
  }

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