【问题标题】:Angular 2 OpaqueToken vs Angular 4 InjectionTokenAngular 2 OpaqueToken vs Angular 4 InjectionToken
【发布时间】:2017-09-11 03:46:03
【问题描述】:

InjectionToken 是在 Angular 4 中引入的,OpaqueToken 被标记为已弃用。

According to the manual,应该是用作

const anyToken = new InjectionToken('any');

对于未键入的令牌,以及作为

const numberToken = new InjectionToken<number>('number');

用于键入的令牌。

但是,typed token 在注入的时候仍然可以被注入和使用不同的类型,TypeScript 就可以了,不是吗?

constructor(@Inject(numberToken) any, @Inject(numberToken) string: string) { ... }

InjectionToken 应该如何从 TypeScript 类型系统中受益?

如果OpaqueToken 两者之间没有实际区别,为什么会被弃用?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    基于InjectionToken 的内部用法,例如here,我假设InjectionToken 在通过injector 实例获取依赖项时为您提供类型检查优势:

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

    【讨论】:

    • 使用这些 injectionTokens 而不是仅仅导入常量有什么好处。我知道这些令牌在测试时很容易被嘲笑?除此之外??只是共享常量的代码很多..
    • @AicoKleinOvink,它似乎只是与 DI 中的提供者相关的令牌的约定。如果您需要在 Angular 的 DI 机制之外的代码中使用常量,只需使用常量
    • @AngularInDepth.com - ('app.config') 只是一个占位符。 app.config 可以是什么?它可以像 let APP_CONFIG = new InjectionToken('types.config');??
    • @Hacker,没错,就是文字描述
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    相关资源
    最近更新 更多