【问题标题】:How can I detect the screen resolution in Angular Universal?如何在 Angular Universal 中检测屏幕分辨率?
【发布时间】:2020-03-28 02:24:48
【问题描述】:

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

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

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

【问题讨论】:

  • 我的解决方案是将屏幕分辨率保存在 cookie 中并将其传递给服务器。

标签: node.js angular typescript angular-material angular8


【解决方案1】:

你可以在你的组件上试试这个

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

// Constructor
constructor() {
    this.getScreenSize();
}

【讨论】:

    【解决方案2】:

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

    @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)
         }
    }
    

    Detect window size using Angular 4 How to get height and width of device display in angular2 using typescript?

    【讨论】:

    • 我想在服务器渲染的那一刻做,用户有两张个性化的图像,并根据他选择的分辨率。
    【解决方案3】:

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

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

    <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>
    

    codepen上的演示

    【讨论】:

    • 我想在服务器渲染的那一刻做,用户有两张个性化的图像,根据他选择的分辨率,如果我在浏览器中这样做,图像可能不匹配。
    • 就是这样,在服务器渲染的时候,没有视口。服务器不知道浏览器窗口的宽度,只有浏览器知道
    • 我有这个问题,我需要背景图像这样的图像。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2011-01-15
    • 2017-12-13
    • 1970-01-01
    相关资源
    最近更新 更多