How to update dependency injection token value
If you don't want to use a BehaviorSubject
, you could provide a simple class with a getter and setter instead.
class MyValue {
get value(): string {
return this._value;
}
set value(val: string) {
this._value = val;
}
private _value = '';
}
const MY_VALUE_TOKEN = new InjectionToken<MyValue>('MY_VALUE_TOKEN ');
// Provide class in either module or component providers array.
providers: [
{ provide: MY_VALUE_TOKEN , useClass: MyValue },
]
class MyComponent {
// Inject in component constructor
constructor(
@Inject(MY_VALUE_TOKEN) private _myValue: MyValue,
) {
// Access current value
console.log(this._myValue.value);
// Set new value
this._myValue.value = 'new value';
}
}
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:
providers: [{ provide: MyValueToken, useValue: new BehaviorSubject('')}]
// consumer
constructor(@Inject(MyValueToken) my_value: BehaviorSubject) {
my_value.subscribe((my_value)=>this.title = my_value);
}
// producer
constructor(@Inject(MyValueToken) my_value: BehaviorSubject) {
my_value.next('my title value');
}
In addition to the Wizard:
If you have a use-case where every consumer needs its own instance of BehaviourSubject. (I happen to be in this use-case). Make sure you define a factory.
const myFactory = () => { return new BehaviorSubject<string>('') };
providers: [
{ provide: MyValueToken, useFactory: myFactory }
]
// Then, as proposed in the top-answer.
// consumer
constructor(@Inject(MyValueToken) my_value: BehaviorSubject) {
my_value.subscribe((my_value)=>this.title = my_value);
}
// producer
constructor(@Inject(MyValueToken) my_value: BehaviorSubject) {
my_value.next('my title value');
}