为什么 ReplaySubject 在 ngOnInit 上被调用?

Why ReplaySubject is getting called on ngOnInit?

我正在尝试在 2 个组件之间进行交互,即 header 组件和包含反应形式的 router-outlet 组件。几天前,经过大量研究,我得到了一个答案,告诉我使用共享服务并且需要一个 ReplaySubject 变量。这将充当 Observable,将在 router-outlet 中的组件的 ngOnInit 中调用。所以问题就出现在这里。一切正常,但刚刚在测试时发现了一个小错误。单击 header 中的按钮后,事件在主要组件中触发,但它一直保持活动状态,直到我硬重新加载页面。 下面是我的代码:

shared.service.ts

public updateSrc = new ReplaySubject<any>(1);
public updateClick = this.updateSrc.asObservable();

header.component.ts(这里点击一个按钮)

update() {
  return this.dataService.updateSrc.next(true);
}

main.component.ts(这里的主要操作发生在点击 header 按钮时)

updateClicked = new Subject<any>();

ngOnInit() {
  this.dataService.updateClick.pipe(takeUntil(this.updateClicked)).subscribe({
    next: value => console.log(value); // At first click of button this happening perfectly but if coming from different route & had clicked the header button previously this thing is getting triggered
  });
}

ngOnDestroy() {
  this.updateClicked.next(); // Closing subscription here
}

谁能告诉我如何重置它?

ReplaySubject(和 BehaviorSubject)存储以前发出的值,并在添加新订阅者时发出这些值。

如果您不希望新订阅者收到以前发出的值,您可以随时使用 Subject,它不存储发出的值。

您可能想阅读有关 the docs 中可用变体的更多信息。