random0620
random0620

Reputation: 1686

How can I check if Angular is running on production server vs localhost

I want some variables that Angular 4 uses to be different depending on whether I am running the app on the production server or on localhost for development. How can I do this? For node.js, I use environment variables but I am not sure if it is possible to use similar environment variables for an Angular web app. What is the best way to approach setting Angular to production without explicitly setting it then deploying?

Upvotes: 10

Views: 15360

Answers (2)

Peter Morris
Peter Morris

Reputation: 23234

In the standard project created by Angular-Cli there is a class named 'environment'. You will see you can add different values to the different versions of the class (one is 'production') and the cli will use the correct one when you run

ng build - - prod

Find more info in the docu: https://angular.io/guide/deployment#enable-production-mode

Use this code to check for production mode:

import { environment } from '../environments/environment';

console.log(environment.production);

Upvotes: 3

Jota.Toledo
Jota.Toledo

Reputation: 28434

If you called the enableProdMode() method for example in your main.ts file, you can import isDevMode from @angular/core to check if the angular app is running on prod mod or not.

For example

import { Component, isDevMode} from '@angular/core';

@Component({...})
export class HomePageComponent {
  constructor() {
    if(isDevMode()){
        console.log("created new HomePageComponent");
    }
  }
}

Thats one way to check the app mode.

But something that is closer related to environment values are the environment files generated by the angular-cli. With those files you can configurate values that will be setted depending on the mode that you start the live server/build your source. You can find more info in the following link

Upvotes: 19

Related Questions