3

I've built my angular application using ng build --prod and when I tried to launch it, an error appeared saying:

Uncaught Error: Cannot enable prod mode after platform setup.

In my api.service.ts at the top of the service I used isDevMode() in case I am testing on localhost:

if (isDevMode()) {
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      // 'Authorization': "Basic " + btoa(user + ":" + password),
      'Authorization': `Basic ${btoa(`${user}:${password}`)}`,
      'Access-Control-Allow-Origin': '*'
    })
  };
} else {
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Access-Control-Allow-Origin': '*'

    })
  };
}

At main.ts:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

And at the environment.ts:

export const environment = {
  production: false
};

I tried to check this post in stack overflow but no results from it and this post on github.

EDIT

environment.prod.ts:

export const environment = {
  production: true
};
alim1990
  • 4,656
  • 12
  • 67
  • 130

1 Answers1

4

You cannot call isDevMode() before enableProdMode is called (see here).

You are importing AppModule in your main.ts file before calling enableProdMode. That import will in turn import your service file, which has the isDevMode check outside of the class from what I understood.

Try moving the initialisation of httpOptions in your service constructor.

Note If the variable is static and initialised when it's declared, you'll have the same issue.

If you want to leave the initialisation outside of the class, you could check your environment instead

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

 if (environment.production) {
    httpOptions = {

Btw, the header Access-Control-Allow-Origin is a server response header and should not be set on a client side request.

David
  • 33,444
  • 11
  • 80
  • 118
  • So the best way is to wrap the http options inside `envirmment.production` instead of using `isDevMode()`? – alim1990 Apr 29 '20 at 13:39
  • I think so. Have a look here: https://stackoverflow.com/questions/39535386/how-to-check-if-angular-application-running-in-production-or-development-mode – David Apr 29 '20 at 13:42