angulardev-mode

Angular why the built application is giving an error of cannot enable prod mode?


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
};

Solution

  • 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.