加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

依赖注入 – Angular2 – 如何注入窗口到angular2服务

发布时间:2020-12-14 01:06:12 所属栏目:百科 来源:网络整理
导读:我在TypeScript中编写一个将使用localstorage的Angular2服务。并且我想将浏览器窗口对象的引用注入到我的服务中,因为我不想引用任何全局变量。喜欢角1.x $窗口。我怎么做? 这对我目前工作(2017-01,角度2.1.2与AoT,测试角度cli和自定义webpack构建): 首
我在TypeScript中编写一个将使用localstorage的Angular2服务。并且我想将浏览器窗口对象的引用注入到我的服务中,因为我不想引用任何全局变量。喜欢角1.x $窗口。我怎么做?
这对我目前工作(2017-01,角度2.1.2与AoT,测试角度cli和自定义webpack构建):

首先,创建一个注入服务,提供对窗口的引用:

import { Injectable } from '@angular/core';

function getWindow (): any {
    return window;
}

@Injectable()
export class WindowRefService {
    get nativeWindow (): any {
        return getWindow();
    }
}

现在,使用您的根AppModule注册该服务,以便它可以注入无处不在:

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建议。编辑2:更新为角度2.1.2编辑3:添加了AoT注释编辑4:添加任何类型的解决办法说明edit5:更新的解决方案使用WindowRefService修复了一个错误,我得到时使用以前的解决方案与不同的构建

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读