Home > Software design >  access DOCUMENT in useFactory
access DOCUMENT in useFactory

Time:05-07

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/app/app.module.ts

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

 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/app/app.module.ts,src/app/document.service.ts,src/app/hello.component.ts

Thank you

CodePudding user response:

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,
    },
  ],
  • Related