Dear community one more…

less than 1 minute read

Dear community, one more question: Is there a best practice for dealing with environment variables in an angular nx monorepo? The environment files are in the app folder and as such not accessible by lib services

Responses:

We make them visible to libs using injection tokens.

do you have an example of how that’s done?

I’ve been using various techniques… For example, move your environment to a shared lib, and update the fileReplacements in your angular.json / workspace.json that’s probably the most straightforward/mechanical way I know if

Well, something like this quick example

```import { Component, InjectionToken, NgModule } from ‘@angular/core’;

export const ENV_VARIABLE = new InjectionToken<string>(‘my-var’);

@Component({}) export class ExampleComponent {

constructor(@Inject(ENV_VARIABLE) private _envVar: string) {}

}

@NgModule({ providers: [ {provide: ENV_VARIABLE, useValue: ‘VALUE’} ] }) export class AppModule {}```

If you provide the tokens in the main module, either directly with the providers array or in a ModuleWithProviders call, ther became accessible via the injector.

Thanks for the example, I can see how that would work well for the content of environment.ts too :slightly_smiling_face:

Thank you! I‘m gonna try this

Updated: