typescript 在 Ionic 2 / Angular 2 beta 10 中访问窗口对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38767595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:43:21  来源:igfitidea点击:

Accessing window object in Ionic 2 / Angular 2 beta 10

javascriptangulartypescriptionic2ionic3

提问by Akilan Arasu

In Angular 1.x and Ionic 1.x I could access the window object through dependency injection, like so:

在 Angular 1.x 和 Ionic 1.x 中,我可以通过依赖注入访问 window 对象,如下所示:

angular.module('app.utils', [])

.factory('LocalStorage', ['$window', function($window) {
    return {
        set: function(key, value) {
          $window.localStorage[key] = value;
        },
        get: function(key, defaultValue) {
          return $window.localStorage[key] || defaultValue;
        }
    };
}]);

How can I do the same in Angular 2 & Ionic 2?

我如何在 Angular 2 和 Ionic 2 中做同样的事情?

回答by sebaferreras

You can use the windowobject without importing anything, but by just using it in your typescript code:

您可以在window不导入任何内容的情况下使用该对象,而只需在您的打字稿代码中使用它:

import { Component } from "@angular/core";

@Component({
     templateUrl:"home.html"
})
export class HomePage {

  public foo: string;

  constructor() {
    window.localStorage.setItem('foo', 'bar');

    this.foo = window.localStorage.getItem('foo');
  }
}

You could also wrap the windowobject inside a service so then you can mock it for testing purposes.

您还可以将window对象包装在服务中,以便您可以模拟它以进行测试。

A naive implementation would be:

一个天真的实现将是:

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

@Injectable()
export class WindowService {
  public window = window;
}

You can then provide this when bootstrapping the application so it's available everywhere.

然后您可以在引导应用程序时提供它,以便它在任何地方都可用。

import { WindowService } from './windowservice';

bootstrap(AppComponent, [WindowService]);

And just use it in your components.

只需在您的组件中使用它。

import { Component } from "@angular/core";
import { WindowService } from "./windowservice";

@Component({
     templateUrl:"home.html"
})
export class HomePage {

  public foo: string;

  constructor(private windowService: WindowService) {
    windowService.window.localStorage.setItem('foo', 'bar');

    this.foo = windowService.window.localStorage.getItem('foo');
  }
}

A more sophisticated service could wrap the methods and calls so it's more pleasant to use.

更复杂的服务可以包装方法和调用,因此使用起来更愉快。