angular - 如何在angular8中取消订阅行为主题
问题描述
嗨,我正在使用 Angular8 应用程序,其中我使用了 Replay 主题和 Behavior 主题,对于初始点击它只点击 api 1 次,但是如果我在选项卡之间切换,订阅点击 fr 多次,如果我点击了选项卡3 次,API 被点击了 6 次,所以它开始成倍增加,有没有办法取消订阅行为主题,我希望 API 只点击一次,我尝试取消订阅,但它没有工作。
TS: App.component.ts:
_otherTab: ReplaySubject<any> = new ReplaySubject();
other() {
this.othertab = 2;
this._otherTab.next(2);
}
HTML:
<div class="card-header bg-dark border-bottom-0">
<ul class="nav nav-tabs nav-fill card-header-tabs" id="" role="tablist">
<li class="nav-item">
<a class="nav-link active" data-toggle="tab" href="#basic" role="tab">User</a>
</li>
<li class="nav-item" (click)="other()">
<a data-toggle="tab" href="#eo" role="tab"
[ngClass]=" {'nav-link':(true),'disabled' : (_otherTabEnabled === false) }" >Other</a>
</li>
</ul>
</div>
<div class="tab-pane" id="eo" role="tabpanel">
<app-other-table [othertab]="_otherTab"></app-other-table>
</div>
其他组件:
@Input() othertab: BehaviorSubject<any>;
ngOnInit() {
this.othertab.subscribe(val => {
if (val) {
this.showTab = true;
}
});
}
解决方案
在您订阅的其他组件中,您必须记住取消订阅。否则您可能会遇到内存泄漏问题等。
所以在你有订阅的地方,记得取消订阅。
subs;
@Input() othertab: BehaviorSubject<any>;
ngOnInit() {
this.subs = this.othertab.subscribe(val => {
if (val) {
this.showTab = true;
}
});
}
ngOnDestroy(){
this.subs.unsubscribe();
}
推荐阅读
- python - 熊猫:用列最大值替换列中的所有值
- python-3.x - ALB 指标的异常检测
- node.js - 我使用 yarn add,nodeJS 告诉我整个文件夹的“找不到模块”
- python - 如何从流式推文中获取全文?
- python - 如何使用python计算重复行并比较excel中的两列值
- mysql - 如何在触发器操作中使用 WHEN 条件
- deployment - PhpStorm 项目中的多个内容根 - 可以合并部署吗?
- html - Django-ckeditor 的内容在管理页面中没有被设置为 html 样式
- r - 重新打印 capture.output(glimpse(df)) 看起来与 glimpse(df) 相同
- python - Python dataclasses.replace 不适用于 InitVar