您可以在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');
}
}
您还可以将对象包装在window
服务中,以便您可以模拟它以进行测试。
一个天真的实现是:
import { Injectable } from '@angular/core';
@Injectable()
export class WindowService {
public window = window;
}
然后,您可以在引导应用程序时提供它,以便它在任何地方都可用。
import { WindowService } from './windowservice';
bootstrap(AppComponent, [WindowService]);
只需在您的组件中使用它。
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');
}
}
更复杂的服务可以包装方法和调用,因此使用起来更愉快。