简体   繁体   English

角度:注入不透明令牌

[英]Angular: Inject an opaque token

I try to understand how I could inject an opaque token. 我试图了解如何注入不透明令牌。

For instance, I have some service MyService, and I create an opaque token for it: 例如,我有一些服务MyService,并为其创建一个不透明令牌:

import {OpaqueToken} from '@angular/core'; 
...
const serviceToken = new OpaqueToken('MyService');
...
providers: [
    {
        provide: serviceToken,
        useValue: 'Service value!'
    }
]

It's ok. 没关系。 But how I could inject this service into my component? 但是如何将这项服务注入到我的组件中呢?

I tried to create the same instance of an Opaque Token in my component and inject it but I got an error: Error: No provider for Token MyService! 我尝试在组件中创建不透明令牌的相同实例并将其注入,但出现错误:错误:令牌MyService没有提供者!

Please, you could review an example: Plunker 请,您可以查看一个示例: Plunker

Conclusion: We could use the same instance of an opaque token in component. 结论:我们可以在组件中使用不透明令牌的相同实例。 Just export it from the module and use in a component. 只需将其从模块导出并在组件中使用即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM