Search code examples
angulartypescriptangular5angular2-nativescript

Environment variables using in Nativescript with Angular 5


I want to use the environment data in my native script with Angular application. I face the below error as "ReferenceError: process is not defined".

Run the application

 npm run android --env.apiUrl="https://******.com/" --env.apiUserName="****" --env.apiPassword="*******"

Angular service

    import { } from 'node';
declare var process: any;

@Injectable()
export class CommonService {
  apiUrl: string;
  userName: string;
  password: string;
  platform: string;

  constructor ()  {


    this.apiUrl = (typeof process !== 'undefined' && process && process.env) ? process.env['apiUrl'] : '';
    this.userName = (typeof process !== 'undefined' && process && process.env) ? process.env['apiUserName'] : '';
    this.password = (typeof process !== 'undefined' && process && process.env) ? process.env['apiPassword'] : '';
    console.log('API URL-->' + this.apiUrl);
    console.log('API USERNAME-->' + this.userName);
    console.log('API PASSWORD-->' + this.password);
    console.log(process.env);

    if (isAndroid) {
        this.platform = 'android';
    } else if (isIOS) {
        this.platform = 'ios';
    }
  }

I am not able to take the apiuRL , apiUserName and apiPassword which I have passed when running the application as the environment. I have referred the below StackOverflow question. But, unlucky. Anybody help me how to take those data from the environment.

stackoverflow link


Solution

  • I am not a nativescript developer but i know Angular way to do this.

    You can use environment.ts and environment.prod.ts, where you put all the environment related variables like apiUserName and apiUrl .. etc.

    In your service you should import the environment and use it in typescript normal way.

    For more details check the following link: https://alligator.io/angular/environment-variables/

    Hope this will inspire you and solve your problem.

    Update

    If you are using webpack you can access process.env in your webpack configuration.

    modules.exports = (env) => {
        let apiUrl = env.apiUrl;
        return {
            entry: '', 
            ......
        }
    }
    

    Now once you have access your env in the webpack configuration, you have many choices to pass them to an angular application.

    1. Use webpack.DefinePlugin (recommended). https://github.com/gdi2290/angular-starter/issues/386

    2. Use fs to write on json file and then read from it in angular application using http.