问题描述
我在TypeScript中编写一个Angular2服务,将使用localstorage。而且我想将浏览器窗口对象引用到我的服务中,因为我不想引用任何全局变量。像角1.x $ window
。我如何做到这一点?
I'm writing an Angular2 service in TypeScript that will make use of localstorage. And 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?
推荐答案
这对我来说正在工作(2017-04,有角度的4.0.2与AoT,测试在角度和自定义webpack构建中):
This is working for me currently (2017-04, angular 4.0.2 with AoT, tested in angular-cli and a custom webpack build):
首先,创建一个可注入的服务,提供对窗口的引用:
First, create an injectable service that provides a reference to window:
import { Injectable } from '@angular/core';
function getWindow (): any {
return window;
}
@Injectable()
export class WindowRefService {
get nativeWindow (): any {
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 {}
然后稍后您需要注入窗口
:
import { Component} from '@angular/core';
import { WindowRefService } from './window-ref.service';
@Component({ ... })
export default class MyCoolComponent {
private _window: Window;
constructor (
windowRef: WindowRefService
) {
this._window = windowRef.nativeWindow;
}
public doThing (): void {
let foo = this._window.XMLHttpRequest;
}
...
编辑:
更新了Truchainz的建议。
edit2:
更新角2.1.2
edit3:
添加AoT注释
edit4:
添加 any
类型变通办法
edit5:更新的解决方案,以使用WindowRefService来修复使用以前的解决方案与不同的构建时遇到的错误
这篇关于Angular2 - 如何将窗口注入到角度2服务中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!