0

So I have an angular application and I've created a hybrid android application using PhoneGap. But currently, I have one issue -

In the angular code, there are many places in the service and controller files where API calls are made. Now, the path of the server from where the API call is made needs to be configurable i.e making a change to a variable in a single file should reflect the change in all angular files. I'm have an idea of using a variable that could be used like - Say the variable is configurableVar; then the variable could be used as such - http://$rootScope.configurableVar/api/call (I'm not sure whether a rootScope variable could be used with PhoneGap)

Currently the API call is as such - http://serverpath:port/api/call but this serverpath is hard-coded in each controller and service files.

Also, could the config.xml file be used in this case? If yes, then how could I use the variable created in the config.xml in the angular files?

HardikT
  • 735
  • 1
  • 8
  • 24

1 Answers1

0

I had a similar situation, I wanted to separate variable values from production/development environment.

Instead of use $rootScope.configurableVar, you should use angular constants. First update your API url references with an angular constant.

Then you can generate the constants file using gulp-ng-config.

For example, lets say you have a config.json file:

{
  "local": {
    "EnvironmentConfig": {
      "api": "http://localhost/"
    }
  },
  "production": {
    "EnvironmentConfig": {
      "api": "https://api.production.com/"
    }
  }
}

Using the plugin is simple as:

gulpNgConfig('myApp.config', {
  environment: 'production'
})

And this will generate the following code:

angular.module('myApp.config', [])
.constant('EnvironmentConfig', {"api": "https://api.production.com/"});

So, to use this with gulp:

var gulp = require('gulp');
var gulpNgConfig = require('gulp-ng-config');
var rename = require('gulp-rename');

gulp.task('config:production', function(){
  // this will generate a www/js/config.js file with production values
  gulp.src('config.json')
    .pipe(gulpNgConfig('myApp.config', { environment: 'production' }))
    .pipe(rename('config.js')) 
    .pipe(gulp.dest('www/js'))
})

To generate angular constants, in terminal just use the following:

gulp config:production

And to use the constants in your angular.js application just:

angular.module('myApp.controllers').controller('myController', ['EnvironmentConfig', '$http', function(EnvironmentConfig, $http){
  $http.get(EnvironmentConfig.url + '/path');
}])
muZk
  • 2,908
  • 1
  • 21
  • 22