Angular: can we remove all the constructor-based injection?

Discussão em 'Angular' iniciado por fservantdev, Novembro 18, 2024.

  1. fservantdev

    fservantdev Guest

    Recently, Angular put in place a migration to replace constructor-based injection with inject function:
    https://angular.dev/reference/migrations/inject-function

    In most of the cases, it is straightforward and it clearly has benefits:

    // before
    @Injectable({ providedIn: 'root' })
    export class SomeSearchService {
    constructor(
    @Inject(SEARCH_DUE_TIME)
    private readonly dueTime: number,
    private readonly repositoryService: SomeRepositoryService
    ) {}

    // after
    @Injectable({ providedIn: 'root' })
    export class SomeSearchService {
    private readonly dueTime = inject(SEARCH_DUE_TIME);
    private readonly repositoryService= inject(SomeRepositoryService);


    However, can inject function cover all the constructor-based injection usages?
    In particular with useFactory?

    To illustrate, I have:

    // print.service.ts
    @Injectable()
    export class PrintService implements IPrintService {
    constructor(
    @Inject(DATA_SERVICE)
    private readonly dataService: IDataService,
    private readonly logger: LoggingService,
    ...
    ) {}

    // tokens.ts
    export const DATA_SERVICE = new InjectionToken<IDataService>('DATA_SERVICE');
    export const FOO_PRINT_SERVICE = new InjectionToken<IPrintService>('FOO_PRINT_SERVICE');
    export const BAR_PRINT_SERVICE = new InjectionToken<IPrintService>('BAR_PRINT_SERVICE');

    // app.config.ts
    export const appConfig: ApplicationConfig = {
    providers: [
    {
    provide: FOO_PRINT_SERVICE,
    useFactory: (dataService: IDataService, logger: LoggingService) => new PrintService(dataService, logger),
    deps: [FOO_DATA_SERVICE, LoggingService],
    },
    {
    provide: BAR_PRINT_SERVICE ,
    useFactory: (dataService: IDataService, logger: LoggingService) => new PrintService(dataService, logger),
    deps: [BAR_DATA_SERVICE, LoggingService],
    },
    ...,
    ],
    };


    Is there a way to use inject & useFactory together
    so that I can remove the constructor declaration in my PrintService?

    Continue reading...

Compartilhe esta Página