1.0.2 • Published 3 years ago
@testdozer/ng-injector-types v1.0.2
This package contains extended types for the Angular injector.
npm install @testdozer/ng-injector-types -D
TypeofInjectionToken
InjectionToken is parameterized on T which is the type of object which will be returned by the Injector. This provides additional level of type safety.
So TypeofInjectionToken returns type T of InjectionToken.
import { InjectionToken } from "@angular/core";
import { JsonObject } from "@angular-devkit/core";
import { ISchema } from "../schema";
export const OPTIONS = new InjectionToken<JsonObject & ISchema>("Options");
@Injectable()
export class Options {
constructor(@Inject(OPTIONS)
private readonly options: TypeofInjectionToken<typeof OPTIONS>) {
}
factory() {
// this.options is strongly typed with type of JsonObject & ISchema
const {project} = this.options;
}
}
InjectionFactory
Provides ability to use an injection factory in form of classes.
@Injectable()
export class Options implements InjectionFactory {
constructor(@Inject(OPTIONS)
private readonly options: TypeofInjectionToken<typeof OPTIONS>) {
// returns an object for the injector
return this.factory() as any;
}
async factory() {
const {project} = this.options;
return {
sourceRoot: `/${project}`
};
}
}
and here the way how to use it
import { TypeOfInjectionFactory } from "ng-injector-types";
import { Options } from "./options";
import { Inject } from "@angular/core";
export class PrivateFilesProvider {
constructor(
@Inject(Options)
private readonly options: TypeOfInjectionFactory<Options>) {
}
async get() {
const {sourceRoot} = await this.options;
}
}
or
import { TypeOfInjectionFactory } from "ng-injector-types";
import { Options } from "./options";
import { Inject } from "@angular/core";
export class PrivateFilesProvider {
constructor(
private readonly options: Options) {
}
async get() {
const {sourceRoot} = await (this.options as TypeOfInjectionFactory<Options>);
}
}