schmoopy
schmoopy

Reputation: 6649

Angular how do I inject API base url

Perhaps I am just thinking of this in the wrong terms, but I don't seem to be able to find the right answer to my question:

"How do I inject an API url into my service?"

Specifically in .NET I would create values in the .config file and use transforms to transform that value for the appropriate environment (debug, QA, PROD) then inject that value.

For AngularJS the only thing I can think to do is create a value service with the endpoints per environment and then ? - or use Grunt to change the value (how will it know what environment its in though).

I'm pretty new to Angular so trying to wrap my head around how deployments to different environments will work. Please not that the Angular site is NOT hosted on the same server as the API, thus I cannot use relative paths.

Thanks in advance

Upvotes: 0

Views: 2122

Answers (2)

DanNut
DanNut

Reputation: 111

Although, it's an old post but I thought someone might find it useful later on, I had a similar architecture where I had to point to different API URLs on the website and I was able to solve it using the following post

http://newtriks.com/2013/11/29/environment-specific-configuration-in-angularjs-using-grunt/

Update:

In summary you can Install environment config generator or create those files manually

npm install generator-env-config

and Create the config file, if you have installed the generator using

yo env-config:development 

Then you use grunt-replace in Grunt.js to replace different config file, just like you do with .Net config files E.g

replace: {
development: {
        options: {
          patterns: [{
            json: grunt.file.readJSON('./config/environments/development.json')
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['./config/config.js'],
          dest: '<%= yeoman.app %>/scripts/services/'
        }]
      },
uat: {
        options: {
          patterns: [{
            json: grunt.file.readJSON('./config/environments/uat.json')
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['./config/config.js'],
          dest: '<%= yeoman.app %>/scripts/services/'
        }]
      },
}

now if you run grunt replace:development, you should have the config file from development Hope this helps

Upvotes: 1

madhured
madhured

Reputation: 443

use the grunt-env plugin: https://npmjs.org/package/grunt-env

and set your config:

grunt.initConfig({
  env : {
    options : {
      //Shared Options Hash
    },
    dev : {
      NODE_ENV : 'development',
      DEST     : 'temp'
    }
  },
  'another-task': {}
});

I found the answer from this link:

NodeJS environment variables in Grunt

Upvotes: 0

Related Questions