在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
本身来完成?
答案 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()
。