我应该在Angular的flex-layout中退订MediaObserver订阅吗?

时间:2020-01-10 14:33:43

标签: angular observable angular-flex-layout

在Angular组件中,我使用以下代码根据屏幕分辨率显示不同的元素:

constructor(private mediaObserver: MediaObserver) {}

private mySubscription: Subscription;

public ngOnInit(): void {
    this.mySubscription = this.mediaObserver.asObservable().subscribe(() => {
        if (this.mediaObserver.isActive('gt-md')) {
          // Do some stuff...
        }
      }
    );
  }

我的问题是,我是否需要从mySubscription中的ngOnDestroy()退订,还是MediaObserver本身来完成?

1 个答案:

答案 0 :(得分:3)

来自README.md(https://github.com/angular/flex-layout/wiki/MediaObserver)中的示例

export class MyDemo implements OnDestroy {
  watcher: Subscription;
  activeMediaQuery = '';

  constructor(mediaObserver: MediaObserver) {
    this.watcher = mediaObserver.media$.subscribe((change: MediaChange) => {
      this.activeMediaQuery = change ? `'${change.mqAlias}' = (${change.mediaQuery})` : '';
      if ( change.mqAlias == 'xs') {
         this.loadMobileContent();
      }
    });
  }

  ngOnDestroy() {
    this.watcher.unsubscribe();
  }

  loadMobileContent() { 
    // Do something special since the viewport is currently
    // using mobile display sizes
  }
}

是的,您需要退订ngOnDestroy()