0
\$\begingroup\$

In some components and services I need the window and document. So I created a small service, that provides these two objects.

windowAndDocument.service.ts:

import { Inject, Injectable } from '@angular/core';

import { DOCUMENT } from '@angular/common';

function getWindow (): any {
  return window;
}

@Injectable({
  providedIn: 'root',
})

export class WindowAndDocumentService {
  public window = null;

  constructor(@Inject( DOCUMENT ) public document :HTMLDocument) {
    this.window = getWindow();
  }
}

This works fine and can be imported into other services.

some.service.ts:

import { Injectable } from '@angular/core';

import { WindowAndDocumentService } from './windowAndDocument.service';

@Injectable({
  providedIn: 'root',
})

export class SomeService {
  constructor(private wads: WindowAndDocumentService) {}

  soSomething() {
    console.log(this.wads.window);
    console.log(this.wads.document.doctype);
  }
}

My questions are:

  • Is this the optimal way to provide window and document?
  • Can this be written more concisely? I find it kind of odd, that one variable is injected and the other is pulled from a function call.

It's a given that the app runs in the browser.

\$\endgroup\$
0
\$\begingroup\$

Assuming you want a SOLID code and keep the single responsibility principle, you would need to inject window and document separately. A clean way is to provide each of them using the useValue property of your provider:

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [
   { provide: "windowObject", useValue: window}
  ]
})

as already answered on SO: same stuff for the document provider.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.