Angular 2 OpaqueToken vs Angular 4 InjectionToken
发布时间:2020-12-17 08:04:08 所属栏目:安全 来源:网络整理
导读:在Angular 4中引入了InjectionToken,并且OpaqueToken被标记为已弃用。 According to the manual,它应该被用作 const anyToken = new InjectionToken('any'); 对于无类型的令牌,以及 const numberToken = new InjectionTokennumber('number'); 对于键入的
在Angular 4中引入了InjectionToken,并且OpaqueToken被标记为已弃用。
According to the manual,它应该被用作 const anyToken = new InjectionToken('any'); 对于无类型的令牌,以及 const numberToken = new InjectionToken<number>('number'); 对于键入的令牌。 但是,键入的令牌仍然可以在注入时注入并使用不同的类型,TypeScript就可以了,不是吗? constructor(@Inject(numberToken) any,@Inject(numberToken) string: string) { ... } InjectionToken如何从TypeScript类型系统中受益? 如果这两者之间没有实际区别,为什么OpaqueToken会被弃用?
根据InjectionToken的内部用法,例如
here,我假设在通过注入器实例获取依赖关系时,InjectionToken为您提供类型检查优势:
import {Component,InjectionToken,Injector} from "@angular/core"; interface AppConfig { name: string; } let APP_CONFIG = new InjectionToken<AppConfig>('app.config'); let appConfig: AppConfig = {name: 'Cfg'}; @Component({ ... providers: [{provide: APP_CONFIG,useValue: appConfig}] }) export class TestComponent { constructor(injector: Injector) { const config = injector.get(APP_CONFIG); config.s = 'd'; ^^^^^ - Error:(14,16) TS2339:Property 's' does not exist on type 'AppConfig'. } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |