angulartypescriptangular-servicesangular-decoratorangular-di

How to update dependency injection token value


Angular dependency injection let you inject a string, function, or object using a token instead of a service class.

I declare it in my module like this:

providers: [{ provide: MyValueToken, useValue: 'my title value'}]

and I use it like this:

constructor(@Inject(MyValueToken) my_value: string) {
  this.title = my_value;
}

However, how can I update the value from the component and let other components get every time the new value? in other words, I want to simulate the functionality of using something like a BehaviorSubject to emit and receive values.

If this is not possible then what is the use of those injection tokens values if they provide only static data as instead I can simply declare the static value in my component and use it directly.


Solution

  • Instead of a primitive which is immutable, you can use a BehaviorSubject, then access and update it in one component and subscribe in the other:

    export const MY_VALUE_TOKEN = new InjectionToken<BehaviorSubject<string>>('my.Value.token')
    
    providers: [{ provide: MY_VALUE_TOKEN, useValue: new BehaviorSubject('')}]
        
    // consumer
    constructor(@Inject(MY_VALUE_TOKEN) my_value: BehaviorSubject<string>) {
      my_value.subscribe((my_value)=>this.title = my_value);
    }
    
    // producer
    constructor(@Inject(MY_VALUE_TOKEN) my_value: BehaviorSubject<string>) {
      my_value.next('my title value');
    }