Import InjectionToken:

import {InjectionToken} from '@angular/core';
Copy the code

Call the constructor imported from @angular /core to create a new instance:

export const TOKEN_HOST_CLASS_PROVIDER = new InjectionToken<HostTokenComponentService>('TOKEN_HOST_CLASS_PROVIDER');
Copy the code

The Injection constructor implements the Injection constructor:

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;
}
Copy the code

Component constructor definition:

providers: [
    HostComponentService,
    {provide: TOKEN_HOST_CLASS_PROVIDER, useClass: HostTokenComponentService}
  ]
Copy the code

Inject in the Component constructor:

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();
  }
Copy the code

Final running result:

Call InjectionToken constructor, options = undefined:

More of Jerry’s original articles can be found in “Wang Zixi” :