angular - RxJS 订阅管理 - 避免过度订阅
问题描述
如何避免超额订阅?
是否有可用于确保取消订阅任何活动订阅的功能?
clickDown(e) {
this.mouseMoveSubscription = fromEvent(this.elementRef.nativeElement, 'mousemove')
.subscribe((e: MouseEvent) => {
console.log(e);
});
}
解决方案
假设您没有使用async
管道,那么当前接受的模式是使用或者takeUntil
管理takeWhile
您的订阅onDestroy
。
例如:
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { takeWhile } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit, OnDestroy {
unsubscribed = false; // <-- When the component loads, subscriptions are all active.
constructor(private router: Router) { }
ngOnInit(): void {
this.router.events
.pipe(takeWhile(() => !this.unsubscribed)) // <-- Maintain this subscription while the component is not destroyed.
.subscribe(() => {});
}
ngOnDestroy(): void {
this.unsubscribed = true; // <-- When the component is destroyed, unsubscribe all subscriptions bound to this.unsubscribed.
}
}
推荐阅读
- rust - Substrate RPC 中的返回结构
- javascript - 将后端数据库添加到 chrome 扩展
- python - 有没有办法将 for 循环的效率与列表理解的“循环”进行比较?它们会相同吗?
- laravel - 未找到 apache2 ubuntu 服务器 404 上的 Laravel api
- python - 是否可以让 tkinter 窗口透明但上面的小部件是实心的?
- angular - 如何解决依赖?
- java - 给定泛型类型的实例,如何找到实现泛型接口的 Java 类?
- django - 如何在 HTML 页面将多个 kwargs 参数传递给 Django 基于类的视图(ListView)?
- google-cloud-platform - 是否需要为每个需要在 AI 平台上使用 Jupyter 笔记本的用户运行一个谷歌笔记本实例?
- python - 从 cloumn 的唯一值创建多个数据框