如何将窗口注入服务? [英] How to inject window into a service?
问题描述
我正在用TypeScript编写Angular 2服务,它将使用localstorage
.我想将对浏览器window
对象的引用注入到我的服务中,因为我不想引用任何全局变量,例如Angular 1.x $window
.
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
.
我该怎么做?
推荐答案
当前适用于我(2018-03,使用AoT的angular 5.2,在angular-cli和自定义的webpack构建中进行了测试):
This is working for me currently (2018-03, angular 5.2 with AoT, tested in angular-cli and a custom webpack build):
首先,创建一个可注射服务,该服务提供对window的引用:
First, create an injectable service that provides a reference to window:
import { Injectable } from '@angular/core';
// This interface is optional, showing how you can add strong typings for custom globals.
// Just use "Window" as the type if you don't have custom global stuff
export interface ICustomWindow extends Window {
__custom_global_stuff: string;
}
function getWindow (): any {
return window;
}
@Injectable()
export class WindowRefService {
get nativeWindow (): ICustomWindow {
return getWindow();
}
}
现在,使用您的根AppModule注册该服务,以便可以将其注入到任何地方:
Now, register that service with your root AppModule so it can be injected everywhere:
import { WindowRefService } from './window-ref.service';
@NgModule({
providers: [
WindowRefService
],
...
})
export class AppModule {}
,然后在需要注入window
的位置:
and then later on where you need to inject window
:
import { Component} from '@angular/core';
import { WindowRefService, ICustomWindow } from './window-ref.service';
@Component({ ... })
export default class MyCoolComponent {
private _window: ICustomWindow;
constructor (
windowRef: WindowRefService
) {
this._window = windowRef.nativeWindow;
}
public doThing (): void {
let foo = this._window.XMLHttpRequest;
let bar = this._window.__custom_global_stuff;
}
...
如果在应用程序中使用nativeDocument
和其他全局变量,您可能也希望以类似的方式将其添加到此服务.
You may also wish to add nativeDocument
and other globals to this service in a similar way if you use these in your application.
更新了Truchainz的建议.
更新为角度2.1.2
添加了AoT注释
添加any
类型的解决方法说明
edit5:更新了解决方案,以使用WindowRefService修复了我在将以前的解决方案与其他版本一起使用时遇到的错误
edit6:添加示例自定义窗口键入
edit:
Updated with Truchainz suggestion.
edit2:
Updated for angular 2.1.2
edit3:
Added AoT notes
edit4:
Adding any
type workaround note
edit5: Updated solution to use a WindowRefService which fixes an error I was getting when using previous solution with a different build
edit6: adding example custom Window typing
这篇关于如何将窗口注入服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!