Angular - How to dynamically pass environment values inside forRoot in the app.module?

37 views Asked by At

I would like to pass values taken from the related environment file (env.json) in the app.module but these values are not available at the moment of the initialization of the GtmModule (are available several ms after initialization).

I would like to ask which approach should be used to achieve values. I tried @Inject and custom Factory but without luck.

GtmModule.forRoot({
      debug:environment.gaAnalyticsDebug,
      disabled:environment.gaAnalyticsDisabled, // GETTING UNDEFINED HERE
      gtmId: 'XXXX',
      readExtIdCookie: false,
    }),
1

There are 1 answers

1
Selaka Nanayakkara On

Create separate environment files :

environment.staging.ts :

export const environment = {
  production: false,
  gaAnalyticsDebug: 'https://api.staging.com',
  gaAnalyticsDisabled:true
};

In your angular.json file :

"configurations": {
  "production": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.prod.ts"
      }
    ]
  },
  "staging": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.staging.ts"
      }
    ]
  },
  // ...
}

In your app.module.ts :

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

@NgModule({
  declarations: [
    // ...
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    GtmModule.forRoot({
     debug:environment.gaAnalyticsDebug,
     disabled:environment.gaAnalyticsDisabled, // GETTING UNDEFINED HERE
     gtmId: 'XXXX',
     readExtIdCookie: false,
   }),
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}