使用BehaviorSubject时遇到一些麻烦。
在我的应用中,我有一个带有3个标签的横幅,您可以选择三个标签。每个都会显示不同的内容。
因此,为了获得其他组件中选中的选项卡,我决定使用BehaviorSubject,从理论上讲,它将更新tabSelected的值。
所以在我的横幅组件中,我有:
component.html:
<div *ngFor="let tab of tabs">
<div class="tab btn-tab" (click)="setTabSelected(tab)">
</div>
</div>
component.ts
ngOnInit() {
this.setTabSelected(this.tabs[0]);
}
setTabSelected(tab) {
this.shareDataSv.sendTab(tab);
}
在中介服务中,我有:
private tabSubject = new BehaviorSubject(new TabsValues());
tab$ = this.tabSubject.asObservable();
sendTab(tab: TabsValues) {
console.log('Send tab', tab);
this.tabSubject.next(tab);
}
在将重新显示所选标签的组件中:
reciver.component.ts
ngOnInit() {
this.knowSelectedTab();
}
knowSelectedTab() {
this.shareDataSv.tab$.subscribe(data => this.tab = data);
console.log('Selected tab', this.tab);
}
因此,一开始我就完美地获得了预定义标签的值。 但是,当我单击其他选项卡时,我在发送新值的服务中看到了,但是我没有在订阅中获得任何数据。
我在这里留下示例:stackblitz example
任何提示我该怎么办? 谢谢!
P.D .:如果我使用一个间隔作为knowSelectedTab(),则可以看到更改。
答案 0 :(得分:1)
您将立即取消订阅,因此订阅到此结束。您应该取消订阅可观察对象,但是请在OnDestroy
中进行。因此,删除退订:
knowTab() {
this.subscription = this.shareDataSv.tab$.subscribe(data => {
if (data) {
this.tab = data;
console.log('Obatined data',this.tab);
}
});
// remove this!
// this.subscription.unsubscribe();
}
// add this
ngOnDestroy() {
this.subscription.unsubscribe();
}
您分叉的 STACKBLITZ