13

I'm trying to export a constant in angular and I need to set a key whose value will be returned from a service. I tried with following code:

This is my user-config.ts file:

export const USER_CONFIG = {
    username: new UserService().getUsername()
}

And this is my UserService file that I would like to be injected in constant:

export class UserService{
    constructor(someOtherService: SomeOtherService)
    getUsername() {
        return this.someOtherService.getDetails('some/url')
    }
}

I'm not able to work around this problem. Need help.

N.F.
  • 3,844
  • 3
  • 22
  • 53
Kedar Udupa
  • 544
  • 9
  • 27

2 Answers2

7

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

J. Bosi
  • 69
  • 6
Sam Herrmann
  • 6,293
  • 4
  • 31
  • 50
0

Try this. You have to pass the service instance

const va = (userService : UserService) => {
    return {
        username : userService.getUsername()
    }
}

export const eV = va(userService)
RateM
  • 241
  • 1
  • 4
  • 15