VSO*_*VSO 35 angular2-opaquetoken angular
我遇到了'不透明的标记'作为在Angular 2中实现全局常量的解决方案,例如:在Angular 2中定义全局常量
尽管阅读了文档,我似乎无法理解这一点.
使用OpaqueToken比使用字符串作为标记更可取,因为多个提供程序使用与两个不同标记相同的字符串可能导致冲突.
什么?什么是开始的Angular2令牌?所有我得到的谷歌都是JSON网络代币(他们在auth等中的角色等)的答案,据我所知,但显然没有任何关联.
什么是不透明的令牌?它是干什么用的?
PS更多关于不透明标记的文档用于提供常量.然而,他们并没有帮助我.
Gün*_*uer 60
更新Angular4
在Angular4 OpaqueToken中已弃用,将替换为InjectionToken.InjectionToken允许传递泛型类型参数.
export let APP_CONFIG = new InjectionToken<MyConfig>("app.config");
Run Code Online (Sandbox Code Playgroud)
也可以看看
原版的
什么?什么是开始的Angular2令牌?
什么是不透明的令牌?它是干什么用的?
令牌是Angulars依赖注入的提供者的关键.提供者注册了一个密钥,由DI实例化的组件,指令和服务类注入了依赖项,这些依赖项由提供者密钥查找.
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
]
Run Code Online (Sandbox Code Playgroud)
// 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) {}
Run Code Online (Sandbox Code Playgroud)
对象key(APP_CONFIG_2)和OpaqueToken(APP_CONFIG)需要是完全相同的实例.具有相同内容的其他实例将不起作用.这样可以轻松查找声明键的位置以及提供程序和注入目标是否使用相同的键.
对于字符串,它可以是不同的实例,这会带来风险,即在不同的模块中使用相同的字符串值,并可能导致冲突或注入错误的提供程序.
什么是不透明的令牌?它是干什么用的?
不透明令牌用于注入具有相同名称的另一个提供者(服务).
这样可以避免命名冲突.
const MY_HTTP_TOKEN: OpaqueToken = new OpaqueToken('Http');
providers: [
{ provide: MY_HTTP_TOKEN, useClass: Http }
]
constructor(@Inject(MY_HTTP_TOKEN) private myHttpService){}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21584 次 |
| 最近记录: |