@Component({
selector: 'test',
template: `<todos [todos]="todos$ | async"></todos>`
})
export class TestComponent {
constructor(private store: Store) { }
ngOnInit() {
this.todos$ = this.store.select('todos');
}
}
当组件销毁时,async 管道会自动执行取消订阅操作,进而避免内存泄露的风险。
Angular AsyncPipe 源码片段
@Pipe({name: 'async', pure: false})
export class AsyncPipe implements OnDestroy, PipeTransform {
// ...
constructor(private _ref: ChangeDetectorRef) {}
ngOnDestroy(): void {
if (this._subscription) {
this._dispose();
}
}
}
@HostListener
export class TestDirective {
@HostListener('click')
onClick() {
....
}
}
需要注意的是,如果使用 @HostListener 装饰器,添加事件监听时,我们无法手动取消订阅。如果需要手动移除事件监听的话,可以使用以下的方式:
// subscribe
this.handler = this.renderer.listen('document', "click", event =>{...});
// unsubscribe
this.handler();
Finite Observable
当你使用 HTTP 服务或 timer Observable 对象时,你也不需要手动执行取消订阅操作。
export class TestComponent {
constructor(private http: Http) { }
ngOnInit() {
// 表示1s后发出值,然后就结束了
Observable.timer(1000).subscribe(console.log);
this.http.get('http://api.com').subscribe(console.log);
}
}
timer 操作符
操作符签名
复制代码 代码如下:
public static timer(initialDelay: number | Date, period: number, scheduler: Scheduler): Observable
操作符作用
timer 返回一个发出无限自增数列的 Observable,具有一定的时间间隔,这个间隔由你来选择。
操作符示例
// 每隔1秒发出自增的数字,3秒后开始发送 var numbers = Rx.Observable.timer(3000, 1000); numbers.subscribe(x => console.log(x)); // 5秒后发出一个数字 var numbers = Rx.Observable.timer(5000); numbers.subscribe(x => console.log(x));
最终建议
你应该尽可能少的调用 unsubscribe() 方法,你可以在RxJS: Don't Unsubscribe 这篇文章中了解与 Subject 相关更多信息。
具体示例如下:
export class TestComponent {
constructor(private store: Store) { }
private componetDestroyed: Subject = new Subject();
todos: Subscription;
posts: Subscription;
ngOnInit() {
this.todos = this.store.select('todos')
.takeUntil(this.componetDestroyed).subscribe(console.log);
this.posts = this.store.select('posts')
.takeUntil(this.componetDestroyed).subscribe(console.log);
}
ngOnDestroy() {
this.componetDestroyed.next();
this.componetDestroyed.unsubscribe();
}
}
内容版权声明:除非注明,否则皆为本站原创文章。
