如何更新依赖项注入令牌值 [英] How to update dependency injection token value

查看:62
本文介绍了如何更新依赖项注入令牌值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

角度依赖注入使您可以使用令牌而不是服务类来注入字符串,函数或对象.

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'}]

我这样使用它:

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

但是,如何在每次更新新值时从组件中更新值并让其他组件获取?换句话说,我想模拟使用 BehaviorSubject 之类的东西来发送和接收值的功能.

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.

推荐答案

您可以使用 BehaviorSubject 而不是不变的原语,然后在一个组件中进行访问和更新,并订阅其他:

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');
}

这篇关于如何更新依赖项注入令牌值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆