[英]How to unsubscribe behaviour subject in 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;
}
});
}
在您订阅的其他组件中,您必须记住取消订阅。 否则,您可能会遇到 memory 泄漏问题等。
所以在你有订阅的地方,记得取消订阅。
subs;
@Input() othertab: BehaviorSubject<any>;
ngOnInit() {
this.subs = this.othertab.subscribe(val => {
if (val) {
this.showTab = true;
}
});
}
ngOnDestroy(){
this.subs.unsubscribe();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.