導入InjectionToken:
import {InjectionToken} from '@angular/core';
複制
調用從@Angular/core導入的構造器,建立一個新的執行個體:
export const TOKEN_HOST_CLASS_PROVIDER = new InjectionToken<HostTokenComponentService>('TOKEN_HOST_CLASS_PROVIDER');
複制
Injection構造器的實作:
export declare class InjectionToken<T> {
protected _desc: string;
readonly ɵprov: never | undefined;
constructor(_desc: string, options?: {
providedIn?: Type<any> | 'root' | 'platform' | 'any' | null;
factory: () => T;
});
toString(): string;
}
複制
Component構造器裡的定義:
providers: [
HostComponentService,
{provide: TOKEN_HOST_CLASS_PROVIDER, useClass: HostTokenComponentService}
]
複制
在Component 構造函數裡進行注入:
export class HostDecoratorComponent {
constructor(private hostComponentService: HostComponentService, @Inject(TOKEN_HOST_CLASS_PROVIDER) h){
console.log('in HostDecoratorComponent, Host component service got from own Injector: ', hostComponentService, ' HostTokenComponentService: ', h);
h.print();
}
複制
最後運作結果:

調用InjectionToken構造器,options的值為undefined: