如何在 Angular Universal 中检测屏幕分辨率?



我正在尝试在Angular Universal中检测浏览器的屏幕分辨率,但我不明白,在浏览器的一侧,我使用Angular Material的断点观察器,但在服务器上不起作用:

this.breakpointObserver.observe(['(max-width: 575px)']).pipe(filter(result => result.matches == true)).subscribe((result: any) => 
{   
console.log('(max-width: 575px)', result)
this.imageBackground = this.imageBackgroundPortrait;
});

这在服务器上被忽略。有什么建议吗? 谢谢。

当您想更新调整大小时,您必须提及以下内容:

@HostListener('window:resize', ['$event'])
onResize(event) {
this.innerWidth = window.innerWidth;
}

这样的东西绝对应该适用于您遇到的任何设备:

export class Dashboard  {
mobHeight: any;
mobWidth: any;
constructor(private router:Router, private http: Http){
this.mobHeight = (window.screen.height) + "px";
this.mobWidth = (window.screen.width) + "px";
console.log(this.mobHeight);
console.log(this.mobWidth)
}
}

使用 Angular 4 检测窗口大小 如何使用打字稿获取 angular2 中设备显示的高度和宽度?

这在服务器上不起作用,因为在服务器上没有"窗口",没有"视口",所以不会定义它。因此,为什么它在服务器上被忽略。实际上,您在那里不需要它。

您可以考虑做的是使用图片标签。这允许浏览器为视口使用最合适的图像。

<picture>
<source media="(min-width: 1100px)" srcset="https://cdn.dribbble.com/users/31348/screenshots/4892068/newport_1x.jpg" />
<source media="(min-width: 650px)" srcset="https://cdn.dribbble.com/users/107759/screenshots/4891695/iphonex-simple-3_1.gif" />
<img src="https://cdn.dribbble.com/users/1185900/screenshots/4890498/shopping_online_03.png" />
</picture>

代码笔演示

你可以在组件上尝试一下

getScreenSize(event?) {
this.scrHeight = window.innerHeight;
this.scrWidth = window.innerWidth;
console.log(this.scrHeight, this.scrWidth);
}
// Constructor
constructor() {
this.getScreenSize();
}

最新更新