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
windowanddocument? - 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.