使用 Angular Material BreakpointObserver API 比简单的媒体查询有什么好处?

What is the benefit of using the Angular Material BreakpointObserver API over a simple Media Query?

我一直在试验 Angular Material,发现自己质疑使用内置 BreakpointObserver API 比简单的媒体查询有什么好处?

或者与其说更有益,不如说它真正归结为您想要实现的目标?

它通常用于使页面在移动设备和桌面设备上有所不同。例如,您可以在 JavaScript 文件中设置断点并使其对更改做出反应。

例如,如果您尝试在移动设备上的输入字段中搜索,您可以导航到 full-page,而只让用户在桌面设备上搜索

  navigateToSearchPageIfMobile = () => {
    combineLatest([this.isMobile$, this.searchActive$]).pipe(
      takeUntil(this.unsubscribe$),
      filter(([isMobile, active]) => isMobile && active))
      .subscribe(() => {
        this._router.navigate(["./", this._languageService.lang$.value, paths.SEARCH], {queryParams: {search: this.searchText$.value}})
      })
  }

或者只是使用 *ngif

的数据驱动设计

或者您可以制作自己的断点服务:

export class BreakpointService {

    constructor() {
        this.onLoad()
        this.onResize()
    }

    private readonly breakpoints = {
        xs: 0,
        sm: 576,
        md: 768,
        lg: 992,
        xl: 1200
    }

    private currentWidthSub$ = new BehaviorSubject<number>(null)
    public currentWidth$ = this.currentWidthSub$.asObservable()

    isMobile$ = this.currentWidth$.pipe(map(x => x < this.breakpoints.md), distinctUntilChanged())

    currentBreakpoint$ = this.currentWidthSub$.pipe(
        filter(width => width != null),
        map(width => {
            return Object.keys(this.breakpoints).map((key) => {
                return {
                    key: key,
                    value: this.breakpoints[key] - 1
                }
            }).reverse().find(x => x.value < width).key
        }),
        distinctUntilChanged()
    )

    private onResize = () => {
        fromEvent(window, 'resize').subscribe(resize => {
            this.currentWidthSub$.next(resize.currentTarget["innerWidth"])
        })
    }

    private onLoad = () => {
        fromEvent(window, 'load').subscribe(load => {
            this.currentWidthSub$.next(load.currentTarget["innerWidth"])
        })

    }  
}