【发布时间】:2020-11-15 09:23:56
【问题描述】:
我在使用 Angular 组件和 rxjs 订阅时遇到了一个非常奇怪的情况。
我有以下ngOnInit 和ngOnDestroy 函数
ngOnInit() {
zip(this.service.getMessage, this.service.getType)
.pipe(takeUntil(this.componentDestroyed$))
.subscribe(data => {
const notification = new Notification(data[0], data[1]);
this.notifications.push(notification);
});
}
ngOnDestroy(): void {
this.componentDestroyed$.next(true);
this.componentDestroyed$.complete();
}
在服务文件中使用 Source 和 Subject 范例设置值后,订阅处于活动状态,如下所示:
private messageSource = new BehaviorSubject<string>('');
private message = this.messageSource.asObservable();
private typeSource = new BehaviorSubject<number>(-1);
private type = this.typeSource.asObservable();
...
...
set setMessage(message: string) {
this.messageSource.next(message);
}
set setType(type: number) {
this.typeSource.next(type);
}
如预期的那样,初始订阅工作正常。但是,离开组件并导航回同一个组件会在ngOnInit 中再次运行zip 订阅,即使在组件在离开时被销毁之后也是如此。如何防止这种情况发生?我还尝试定义订阅变量并调用unsubscribe。我被难住了。
【问题讨论】:
-
当您导航回组件时,组件会从头开始初始化,
ngOnInit会再次运行。所以很自然地会再次发起订阅。 -
嘿@MichaelD,谢谢。没错。但是,
ngOnInit中的订阅包含在组件被销毁之前发出的先前值。如果我在返回时没有发出任何值,这些值不应该为空吗? -
BehaviorSubject保存当前值(即使它在组件被销毁之前发出)并在订阅时立即发出。如果组件被创建或销毁,服务中的BehaviorSubjects 没有上下文,它们在订阅后立即编辑。如果您希望 observables 仅在 推送一个新值之后发出,您可以使用Subject而不是BehaviorSubject。 -
@MichaelD 我花了几个小时跟踪这个,
BehaviorSubject一直为我的案例工作,除了这次。我一直使用它,但从来不知道BehaviorSubject和Subject之间的细微差别。谢谢!如果您花时间发布,我会接受您的解决方案。 -
不客气 :)。我已经发布了答案。
标签: angular rxjs observable subscription behaviorsubject