Angular SSR window 调整大小事件

Angular SSR window resize event

我正在尝试创建一个 Angular 组件可以用来监视 window 调整大小事件的服务。经过多次尝试,我终于发现这个解决方案效果最好

不过SSR里运行的时候好像报错了

TypeError: this.eventManager.addGlobalEventListener is not a function

经过多次尝试,这就是我所在的位置:

服务

import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { EventManager } from '@angular/platform-browser';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class WindowService {
  private resizeSubject: Subject<Window>;

  constructor(
    @Inject(PLATFORM_ID) private eventManager: EventManager) { // Event is not defined without @Inject(PLATFORM_ID) 
      this.resizeSubject = new Subject();

      this.eventManager.addGlobalEventListener('window', 'resize', this.onResize.bind(this));
  }

  private onResize(event: UIEvent) {
    this.resizeSubject.next(<Window>event.target);
  }

  /**
   * Get an observerable for the window resize event
   * @returns   Return the window resize as an observable
   */
  get onResize$(): Observable<Window> {
    return this.resizeSubject.asObservable();
  }
}

组件

import { Component, ElementRef, Input, OnInit, Output, EventEmitter, OnDestroy } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { Subscription } from 'rxjs/Subscription';

import { WindowService } from '../../services/window.service';


@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html'
})

export class SidebarComponent implements OnInit, OnDestroy {
  element: HTMLElement;
  resizeSubscription: Subscription;

  constructor(
    private readonly el: ElementRef,
    private windowService: WindowService) {
      this.element = el.nativeElement;
  }

  ngOnInit(): void {
    const self = this;

    this.resizeSubscription = this.windowService.onResize$
      .debounceTime(100)
      .subscribe(function(windowObj) {
        if (windowObj.innerWidth >= 1024) {
          self.open();
        } else {
          self.close();
        }
      });
  }

  ngOnDestroy(): void {
    if (this.resizeSubscription) {
      this.resizeSubscription.unsubscribe();
    }
  }

  ...
}

绑定到 window 调整大小事件似乎是一种非常复杂的方法,但我还没有找到与 Angular SRR 一起使用的更好方法。有没有推荐的方法?本质上,我需要在调整大小(以及加载)时检查 window 大小,并相应地打开或关闭侧边栏。

<div (window:resize)="onResize($event)"

方法:

onResize(event) {
  event.target.innerWidth;
}

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

支持的全局目标是 windowdocumentbody

您可以使用 platformId 编写不同的代码服务器和浏览器:

 constructor( @Inject(PLATFORM_ID) private platformId: Object, private eventManager: EventManager) {
      this.resizeSubject = new ReplaySubject();
    if (isPlatformBrowser(this.platformId)) {
      this.eventManager.addGlobalEventListener('window', 'resize', this.onResize.bind(this));
    }
  }

对于用户全局window,文档,事件写成:https://github.com/Angular-RU/angular-universal-starter/blob/6d1e980655a55b2e1651ac5d040aaff80bc8fe8c/server.ts#L13