Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

access DOCUMENT in useFactory

I want to inject @Inject(DOCUMENT) in factory. How to inject it since it is not service therefor I can’t add it in deps.

// import { DOCUMENT } from '@angular/common';
 providers: [
    {
      provide: APP_INITIALIZER,
      deps: [Document],
      useFactory: (): any => (document: Document) => {
        console.log(document);
      },
      multi: true,
    },
  ],

playground: https://stackblitz.com/edit/angular-ivy-dll1cp?file=src%2Fapp%2Fapp.module.ts

I even tried with one service but I am getting cannot read getBody();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 providers: [
    {
      provide: APP_INITIALIZER,
      deps: [DocumentService],
      useFactory: (): any => (document: DocumentService) => {
        console.log(document.getBody());
      },
      multi: true,
    },
  ],

playground with service: https://stackblitz.com/edit/angular-ivy-pyjymc?file=src%2Fapp%2Fapp.module.ts,src%2Fapp%2Fdocument.service.ts,src%2Fapp%2Fhello.component.ts

Thank you

>Solution :

you almost have done the correct variant. DOCUMENT is a token that should be in deps array. And then the document object will be injected into the factory callback

import { DOCUMENT } from '@angular/common';
providers: [
    {
      provide: APP_INITIALIZER,
      deps: [DOCUMENT],
      useFactory: (document: Document): any => () => {
        console.log(document);
      },
      multi: true,
    },
  ],
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading