访问Ionic 2 / Angular 2 beta 10中的窗口对象 [英] Accessing window object in Ionic 2 / Angular 2 beta 10

查看:112
本文介绍了访问Ionic 2 / Angular 2 beta 10中的窗口对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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;
        }
    };
}]);

我如何在Angular 2& Ionic 2?

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

推荐答案

您可以使用窗口对象而无需导入任何内容,但只需在打字稿代码中使用它:

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

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 window object inside a service so then you can mock it for testing purposes.

一个天真的实现将是:

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.

这篇关于访问Ionic 2 / Angular 2 beta 10中的窗口对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆