How to use EventManager to listen to window.resize events in angular?

I'm borrowing some code from this stackoverflow: Angular window resize event The author of the answer says I should be using the EventManager if I want to listen for window events from a service and not break Angular Universal. That being said, is this answer still true? If so, could someone show me why when I subscribe to the onResize$ Observable logs nothing when the window is resized?

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

@Injectable()
export class ResizeService {

  get onResize$(): Observable<Window> {
    return this.resizeSubject.asObservable().filter(_ => !_);
  }

  private resizeSubject: Subject<Window>;

  constructor(private eventManager: EventManager) {
    this.resizeSubject = new Subject();
    this.eventManager.addGlobalEventListener('window', 'resize', this.onResize.bind(this));
  }

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

my-component.ts

export class MenuContainer implements OnInit {

  constructor(private resizeService : ResizeService ) {
  }

  public ngOnInit() {
    this.resizeService.onResize$.subscribe(console.log); // never logs when I resize
  }
}

Answers:

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.