Categories
Angular Answers

How to inject window into a service with Angular?

Spread the love

Sometimes, we want to inject window into a service with Angular.

In this article, we’ll look at how to inject window into a service with Angular.

How to inject window into a service with Angular?

To inject window into a service with Angular, we can inject document into our service.

Then we get window from document.

For instance, we write

import { Inject } from "@angular/core";
import { DOCUMENT } from "@angular/common";

export class MyClass {
  private window: Window;

  constructor(@Inject(DOCUMENT) private document: Document) {
    this.window = this.document.defaultView;
  }

  foo() {
    console.log(this.document);
    console.log(this.window);
  }
}

to inject document with @Inject(DOCUMENT) private document: Document in the constructor signature.

Then we get window from this.document.defaultView in the constructor.

Conclusion

To inject window into a service with Angular, we can inject document into our service.

Then we get window from document.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *