Accessing window object in Ionic 2 / Angular 2 beta 10

前端 未结 1 1881
南旧
南旧 2021-01-05 20:01

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

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

.factory(\'LocalStora         


        
相关标签:
1条回答
  • 2021-01-05 20:29

    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.

    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.

    0 讨论(0)
提交回复
热议问题