BreakpointObserver 未触发

BreakpointObserver not firing

我已经按如下方式设置了我的 BreakpointObserver,但它似乎并没有在我的页面加载时触发。我的页面始终处于移动方向。我该如何解决?

home.component.ts

import { Component, OnInit } from '@angular/core';
import { Breakpoints, BreakpointState, BreakpointObserver } from '@angular/cdk/layout';
import { Observable } from 'rxjs';

@Component({
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  isMobile: Observable<BreakpointState> = this.breakpointObserver.observe(Breakpoints.Handset);

  constructor(private breakpointObserver: BreakpointObserver) { }

  ngOnInit() {
  }
}

home.component.html

<div *ngIf="!isMobile | async">is not mobile</div>

<div *ngIf="isMobile | async">is mobile</div>

因为 isMobile 是一个 Observable,它会解包成这样的值:

{
  "matches": true,
  "breakpoints": {
    "(max-width: 599px) and (orientation: portrait)": true,
    "(max-width: 959px) and (orientation: landscape)": false
  }
}

!前加一个!总是让*ngIf为假

展开的对象将有一个 matches 属性,但是,这是一个 boolean。所以你可以使用那个。

试试这个:

<div *ngIf="!(isMobile | async)?.matches">is not mobile</div>

<div *ngIf="(isMobile | async)?.matches">is mobile</div>

此外,更改 HomeComponent 实现以在 ngOnInit 中初始化 isMobile,因为这是通常遵循的做法:

export class HomeComponent {
  isMobile: Observable<BreakpointState>;

  constructor(private breakpointObserver: BreakpointObserver) { }

  ngOnInit() {
    this.isMobile = this.breakpointObserver.observe(Breakpoints.Handset);
  }

}

这里有一个 Sample StackBlitz 供您参考。