How to inject the environment to a service in an Angular multi module project

123 views Asked by At

I have an Angular project with 2 apps and 2 libs. I have build a service in one of the libs, because I want to use the service in both apps.

The problem is that I need the environment from the environment.ts in the service and the that both apps have different environments.

How can I can inject the correct environment in the service?

1

There are 1 answers

0
enno.void On

You can create an InjectionToken:

const TOKEN = new InjectionToken<YourEnviromentInterface>('env');

Then use this token in your service that is used by both apps:

@Injectable()
export class TestService {
  #env = inject(TOKEN);

  constructor() {
    console.log(this.#env);
  }

}

In the last step you provide a value for this token in both of apps:

App 1:

import {yourEnv} from '../somewhere/app1/env.ts'

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [],
  provides: [
    provide: TOKEN,
    useValue: yourEnv
  ]
})
export class App1Module { }

App 2:

import {yourEnv2} from '../somewhere/app2/env.ts'

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [],
  provides: [
    provide: TOKEN,
    useValue: yourEnv2
  ]
})
export class App2Module { }