我应该取消订阅 Angular 的弹性布局中的 MediaObserver 订阅吗?
Should I unsubscribe from a MediaObserver subscription in flex-layout for Angular?
在 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...
}
}
);
}
我的问题是,我需要在 ngOnDestroy()
中取消订阅 mySubscription
,还是 MediaObserver
自己取消订阅?
来自 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()
后退订。
在 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...
}
}
);
}
我的问题是,我需要在 ngOnDestroy()
中取消订阅 mySubscription
,还是 MediaObserver
自己取消订阅?
来自 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()
后退订。