2017-04-14 7 views
19

InjectionTokenはAngular 4に導入され、OpaqueTokenは非推奨としてマークされました。角2 OpaqueToken対角4注入トーン

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はどのようにタイプスクリプト型システムの恩恵を受けると思われますか?

OpaqueTokenは、これら2つの間に実際的な違いがない場合、なぜ非推奨になったのですか? InjectionTokenの内部の使用に基づいて

答えて

16

は、例えば、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'. 
    } 
}