【问题标题】:matchMedia Is not working when using angular universal for serverside rendering使用 Angular Universal 进行服务器端渲染时,matchMedia 不起作用
【发布时间】:2018-09-23 03:45:04
【问题描述】:

正常角度。我这样做。

export class BasicLayoutComponent implements OnInit {
  private mediaMatcher: MediaQueryList = matchMedia(`(max-width: ${SMALL_WIDTH_BREAKPOINT}px)`);
  @ViewChild(MatSidenav) sidenav: MatSidenav;
  @ViewChildren('sidenav') sidenavs: QueryList<MatSidenav>;

  constructor(private _route: ActivatedRoute,
              private _router: Router,
              zone: NgZone) {
    this.mediaMatcher.addListener(mql => zone.run(() => this.mediaMatcher = mql));

  }
  ngOnInit() {
    this._router.events.subscribe(() => {
      if (this.isScreenSmall()) {
        if (this.sidenavs.first) {
        this.sidenavs.first.close();
        } 
      }
    });
  }

  isScreenSmall(): boolean {
    return this.mediaMatcher.matches;
  }
}

但是当我使用 Angular Universal 进行服务器端渲染时,它不起作用。 我得到错误 ERROR { Error: Uncaught (in promise): ReferenceError: matchMedia is not defined

我该如何解决这个问题?

【问题讨论】:

    标签: angular angular-universal


    【解决方案1】:

    有些变量和函数只在客户端可用,服务器端不可用,例如documentwindow,因为它们是由浏览器定义的。 matchMedia 可能属于此列表

    如果您是客户端,则应修改代码以使用这些变量/函数,使用 platformId 令牌来识别正在执行的代码是客户端还是服务器端

    https://github.com/angular/universal/blob/master/README.md#universal-gotchas

    【讨论】:

    • 我刚读完!他们说他们提供了一个 Very Primitive 版本的窗口对象。据我所知,“原始”版本没有 matchMedia 功能。我不知道他们打算升级那个原始版本。
    猜你喜欢
    • 2021-11-01
    • 2017-04-27
    • 2017-11-22
    • 2016-05-09
    • 2021-06-11
    • 2023-04-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多