本文介绍了Angular 2 OpaqueToken与Angular 4 InjectionToken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

InjectionToken was introduced in Angular 4 and OpaqueToken was marked as deprecated.

根据手册,应该用作

const anyToken = new InjectionToken('any');

用于非类型化令牌,并为

for untyped token, and as

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

用于输入令牌.

但是,键入的令牌在注入时仍然可以注入并以其他类型使用,TypeScript可以接受,不是吗?

However, typed token still can be injected and used with different type when it is injected, TypeScript will be ok with this, won't it?

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

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

How is InjectionToken supposed to benefit from TypeScript type system?

如果这两个之间没有实际区别,为什么不推荐使用OpaqueToken?

Why was OpaqueToken deprecated if there's no practical difference between those two?

推荐答案

基于InjectionToken的内部用法,例如,此处,我假设InjectionToken通过类型为injector的实例获取依赖项时具有类型检查的好处:/p>

Based on the internal usage of InjectionToken, for example, here, I assume that InjectionToken gives you type checking benefit when getting a dependency through injector instance:

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

这篇关于Angular 2 OpaqueToken与Angular 4 InjectionToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 10:24