How to inject a service into a constant in angular
Constants in Angular may be constructed using InjectionToken:
export const USER_CONFIG = new InjectionToken('User Configuration', {
factory: () => {
return {
// You can inject the UserService to get the username
username: inject(UserService).getUsername()
}
}
});
Since the constant is an injection token, it can be injected in other parts of your application:
export class AppComponent {
constructor(@Inject(USER_CONFIG) config) {
console.log(config.username)
}
}
StackBlitz Example