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


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

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

function getWindow (): any {
  return window;

  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.


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

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

  providedIn: 'root',

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

  soSomething() {

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.


bumped to the homepage by Community yesterday

This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.


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:

  declarations: [...],
  imports: [...],
  providers: [
   { provide: "windowObject", useValue: window}

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


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.