简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM