How to inject window into a service?

2020-01-22 16:22发布

I'm writing an Angular 2 service in TypeScript that will make use of localstorage. I want to inject a reference to the browser window object into my service since I don't want to reference any global variables like Angular 1.x $window.

How do I do that?

21条回答
爷、活的狠高调
2楼-- · 2020-01-22 16:57

Angular 4 introduce InjectToken, and they also create a token for document called DOCUMENT. I think this is the official solution and it works in AoT.

I use the same logic to create a small library called ngx-window-token to prevent doing this over and over.

I have used it in other project and build in AoT without issues.

Here is how I used it in other package

Here is the plunker

In your module

imports: [ BrowserModule, WindowTokenModule ] In your component

constructor(@Inject(WINDOW) _window) { }

查看更多
Root(大扎)
3楼-- · 2020-01-22 16:57

There is an opportunity for direct access to the object of window through the document

document.defaultView == window
查看更多
叛逆
4楼-- · 2020-01-22 16:58

You can just inject it after you've set the provider:

import {provide} from 'angular2/core';
bootstrap(..., [provide(Window, {useValue: window})]);

constructor(private window: Window) {
    // this.window
}
查看更多
登录 后发表回答