Skip to content

Instantly share code, notes, and snippets.

@javebratt
Created July 18, 2022 21:49
Show Gist options
  • Save javebratt/5ae42f5f9299e9ed98be1a4056c16136 to your computer and use it in GitHub Desktop.
Save javebratt/5ae42f5f9299e9ed98be1a4056c16136 to your computer and use it in GitHub Desktop.
Example of injector token in nx monorepo
// This is an example in a previous application to show
// how to use the variables in the `environment.ts`
// file in different Nx libraries.
// First, we create the injection tokens in a shared library, for this example, I used the file:
// `libs/shared/util/environment-config/src/lib/app-config.ts`
import { InjectionToken } from '@angular/core';
export const APP_VERSION = new InjectionToken<string>('app-version');
export const HEADER_COLOR = new InjectionToken<string>('header-color');
export const BASE_URL = new InjectionToken<string>('header-color');
// Then, inside of the application itself, we create a service
// to route those tokens `apps/app-name/src/app/services/index.ts`
import { environment } from '../../environments/environment';
import { BASE_URL, APP_VERSION, HEADER_COLOR } from '@jorge/shared/util/environment-config';
import { InjectionToken } from '@angular/core';
export const services: CustomAppProvider[] = [
{ provide: BASE_URL, useValue: environment.httpBaseUrl },
{ provide: APP_VERSION, useValue: environment.appVersion },
{ provide: HEADER_COLOR, useValue: environment.headerColor },
];
interface CustomAppProvider {
provide: InjectionToken<unknown>;
useValue: unknown;
}
// Then to use it, we can freely use it in any library:
import { Inject, Injectable } from '@angular/core';
import { BASE_URL } from '@jorge/shared/util/environment-config';
@Injectable({
providedIn: 'root',
})
export class CustomHttpService {
constructor(@Inject(BASE_URL) private baseUrl: string) {
// You can use it regularly.
console.log(this.baseUrl);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment