gpt4 book ai didi

angular - Angular 2 不透明 token 中有什么,有什么意义?

转载 作者:太空狗 更新时间:2023-10-29 16:49:00 26 4
gpt4 key购买 nike

我遇到了“不透明标记”作为在 Angular 2 中实现全局常量的解决方案,例如:Define global constants in Angular 2

尽管阅读了 docs ,我似乎无法捕获重点。

Using an OpaqueToken is preferable to using strings as tokens because of possible collisions caused by multiple providers using the same string as two different tokens.

什么?什么是 Angular2 token ?我在谷歌上得到的只是关于 JSON Web token 的答案(它们在身份验证等中的作用),我理解,但显然没有任何关系。

什么是不透明 token ?它有什么用?

附言更多 docs在用于提供常量的不透明标记上。然而,它们对我帮助不大。

最佳答案

更新 Angular4

在 Angular4 中,OpaqueToken 已被弃用,将被 InjectionToken 取代。InjectionToken 允许传递泛型类型参数。

export let APP_CONFIG = new InjectionToken<MyConfig>("app.config");

另见

原创

What? What's an Angular2 token to begin with?

What's an Opaque Token? What is it used for?

token 是 Angulars 依赖注入(inject)提供者的 key 。提供程序使用 key 注册,组件、指令和由 DI 实例化的服务类获得注入(inject)的依赖项,这些依赖项由提供程序 key 查找。

DI 支持类型、字符串、OpaqueToken 和对象作为键。

export let APP_CONFIG = new OpaqueToken("app.config");

export let APP_CONFIG_2 = {};

providers: [
MyService, // type is key and value
{provide: MyService, useClass: MyFancyServiceImpl}, // type is key, `MyFancyServiceImpl` is the value (or rather the information how to create the value
{provide: 'myservice', useClass: MyService}, // key is a string
{provide: APP_CONFIG, useValue: {a: 'a', b: 'b'}} // key is an `OpaqueToken`
{provide: APP_CONFIG_2, useValue: {a: 'a', b: 'b'}} // key is an object

]
// one of these decorators needs to be added to make DI work
@Injectable()
@Component()
@Directive()
@Pipe()
class MyComponent {
// DI looks up a provider registered with the key `MyService`
constructor(private myService: MyService) {}

// Same as before but explicit
constructor(@Inject(MyService) private myService: MyService) {}

// DI looks up a provider registered with the key 'myService'
constructor(@Inject('myservice') private myService: MyService) {}

// DI looks up a provider registered with the `OpaqueKey` `APP_CONFIG`
constructor(@Inject(APP_CONFIG) private myConfig: any) {}

// DI looks up a provider registered with the object `APP_CONFIG_2`
constructor(@Inject(APP_CONFIG_2) private myConfig: any) {}

对象键 (APP_CONFIG_2) 和 OpaqueToken (APP_CONFIG) 需要是完全相同的实例。具有相同内容的不同实例将不起作用。这使得查找声明 key 的位置以及提供者和注入(inject)目标是否使用相同的 key 变得容易。

对于一个字符串,它可以是不同的实例,这带来了风险,即相同的字符串值在不同的模块中使用,并可能导致冲突或注入(inject)错误的提供者。

关于angular - Angular 2 不透明 token 中有什么,有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41289264/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com