I finally resolved this issue. I was faced with two options. Option 1 was to use XHR to fetch the api-keys from an end-point on the server. Option 2 is get the api-key directly from environment variables using Nodejs process.env. I prefer option 2 because it saves me from doing XHR request.
You can get option 2 by using this ember-cli-addOn which depends on Nodejs Dotenv project
In my case I choose to do it without any addOn.
- First add the api-key to your
.bashrc
if you are Ubuntu or the approapriate place for your own linux distro.
export API_KEY=NwPyhL5
- Reload the
.bashrc
file, so your setting are picked up:
source ~/.bashrc
- In Ember CLI add a property to the
ENV
object in config/environment.js
. The default looks like this
module.exports = function(environment) {
var ENV = {
modulePrefix: 'rails-em-cli',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
}
}
Now to that ENV
object, we can add a new property myApiKey like this:
module.exports = function(environment) {
var ENV = {
modulePrefix: 'rails-em-cli',
environment: environment,
baseURL: '/',
locationType: 'auto',
myApikey: null,
EmberENV: {
}
//assign a value to the myApiKey
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
ENV.myApiKey = process.env.API_KEY;
}
}
Note that process.env.API_KEY is fetching the setting we added to .bashrc
and assigning it to myApiKey. You will need to have Nodejs installed on your server for process.env to work.
Finally to access that variable in your controller you do
import config from '../config/environment';
import Ember from 'ember';
export default Ember.Controller.extend({
yourKey: config.myApikey,
});
That's it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…