我正在尝试为我的应用程序构建一个可注入的单例服务,它允许所有提供的组件知道窗口的宽度和高度,并识别页面滚动或调整大小的时间。
以下是该服务的代码:
import { Injectable, NgZone } from '@angular/core';
@Injectable()
export class ViewportService {
public viewportHeight: number;
public viewportWidth: number;
public pageTop: number = 0;
public mobile: boolean;
constructor(private ngZone:NgZone) {
this.viewportHeight = window.innerHeight;
this.viewportWidth = window.innerWidth;
if(this.viewportWidth < 1001) {
this.mobile = true;
}
else {
this.mobile = false;
}
window.onresize = (e) => {
ngZone.run(() => {
if(this.viewportWidth < 1001) {
this.mobile = true;
} else {
this.mobile = false;
}
})
}
window.onscroll = (e) => {
ngZone.run(() => {
this.pageTop = window.scrollY;
})
}
}
}
这是实现它的组件:
constructor(private viewportService: ViewportService) {
this.mobile = viewportService.mobile;
this.viewPortHeight = viewportService.viewportHeight;
this.pageTop = viewportService.pageTop;
if(this.mobile) {
this.viewPortHeight = viewportService.viewportHeight - 70;
}
else {
this.viewPortHeight = viewportService.viewportHeight - 270;
}
}
服务在页面加载时成功注入数据,但在窗口事件发生时不会更新组件。我是否需要手动告诉我的组件观察ViewportService以进行更改?
答案 0 :(得分:1)
下面的代码对组件执行一次,并从服务中复制值,然后忽略该服务。 这些是原始值,它们是按值而不是通过引用复制的。
if(this.mobile) {
this.viewPortHeight = viewportService.viewportHeight - 70;
}
else {
this.viewPortHeight = viewportService.viewportHeight - 270;
}
也许您希望在组件可以订阅的服务中使用Observable,以获得有关更改的通知。 有关示例,请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html
是的。 NgZone
可用于单例服务。整个Angular2应用程序只有一个区域。