Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the json config file inside angular module?

I am writing the javascript, AngularJS app using typescript. Also I am using grunt for building. In fact I have started off with ng boilerplate.

Now suppose I have a config.json file something like below-

{
    "app": "abc",
    "login": "xyz" 
}

I want some variables in my app to be configurable. So at some place I could use something like -

var loginUrl : string = "def?pqr="+config.app;

Now how can I read this config in my javascript files? I am looking for best practice answer. I am fine with substitution at grunt build step also.

Note: The config file is present on client itself, i.e no need to load it from server separately.

like image 370
Vinayak Garg Avatar asked Sep 23 '14 06:09

Vinayak Garg


People also ask

How do I open a JSON config file?

In the Project Explorer view, expand the plug-in project node. Expand the plugin folder node. Double-click the config. json file, or right-click the file and select Open with > PDK JSON Editor.

What is config json file in Angular?

The angular. json file at the root level of an Angular workspace provides workspace-wide and project-specific configuration defaults. These are used for build and development tools provided by the Angular CLI. Path values given in the configuration are relative to the root workspace directory.


1 Answers

In my case, I use grunt to inject a config file (shared with the server) in an angular constant module :

Using grunt-preprocess :

I having a config.tpl.js with :

angular.module('app.config', [])

.constant('appConfig', {

    // clientside specific constants
    var1                        : 'value1',
    var2                        : [1,2,3],
    sharedVars                  : /* @echo SHARED_VARS */
});

Then, in my gruntFile :

preprocess: {
    options: {
        context: {
            SHARED_VARS: grunt.file.read('config.json'),
        }
    },
    config: {
        src: 'src/config.tpl.js',
        dest: 'src/config.js' // true file generated and loaded in index.html
    }
},

That way you can inject a full config file in an angular constant module, or pick only the vars you want.

like image 73
Jscti Avatar answered Oct 12 '22 23:10

Jscti