我以为我也投入了两分钱。我使用这种模式:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'my-component',
templateUrl: 'my.component.html'
})
export class MyComponent implements OnInit, OnDestroy {
private subscriptions: Array<Subscription> = [];
public ngOnInit(): void {
this.subscriptions.push(this.someService.change.subscribe(() => {
[...]
}));
this.subscriptions.push(this.someOtherService.select.subscribe(() => {
[...]
}));
}
public ngOnDestroy(): void {
this.subscriptions.forEach((subscription: Subscription) => {
subscription.unsubscribe();
});
}
}
编辑
前几天,我阅读了文档,发现了一个更推荐的模式:
ReactiveX / RxJS /订阅
优点:
它在内部管理新的订阅并添加一些简洁的检查。在功能中会首选此方法:)。
缺点:
目前尚不清楚100%是什么代码流以及如何影响订阅。也不清楚(仅通过查看代码)它如何处理封闭的订阅,如果调用了unsubscribe,所有订阅是否都将关闭。
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'my-component',
templateUrl: 'my.component.html'
})
export class MyComponent implements OnInit, OnDestroy {
private subscription: Subscription = new Subscription();
public ngOnInit(): void {
this.subscription.add(this.someService.change.subscribe(() => {
[...]
}));
this.subscription.add(this.someOtherService.select.subscribe(() => {
[...]
}));
}
public ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}