我有一个包含 2 个组件应用程序和主页的应用程序。
在应用程序中,我有一个侧边菜单,当单击一个项目时,它会更新我用作简单存储的 UIService 中的行为主题。
在 home 组件中,我订阅了商店,目前只是将其记录到控制台。
每次我点击一个菜单项时,home 组件中的订阅都会被调用两次。我已经使用 takeUntil 或 take 看到了对此的其他答案。
home 组件不会被销毁,所以我不能使用 ngOnDestroy 取消订阅。
如果我使用 take(1) 那么它不会记录任何内容。
app.component.ts
selectTechnique(technique){
this.uiService.selectTechnique(technique)
}
ui-service.service.ts
private _stateSource$ = new BehaviorSubject<UIState>({
selectedTechniqueTitle: '',});
state$ = this._stateSource$.asObservable();
//action
selectTechnique(technique) {
this._stateSource$.next({
...this._getcurrentState(),selectedTechniqueTitle: technique.title,});
}
// Select
selectSelectedTechnique() {
return this.state$.pipe(map((state) =>
state.selectedTechniqueTitle));
}
private _getcurrentState(): UIState {
return this._stateSource$.value;
}
home.component.ts
ngOnInit(): void {
this.uiService.selectSelectedTechnique().subscribe(val => {
console.log('SelectedTechnique',val); // This logs twice
})
// or
this.uiService.selectSelectedTechnique().pipe(take(1)).subscribe(val => {
console.log('SelectedTechnique',val); // This does not log anything
})
}
如何只获取一次数据?我需要在此订阅中执行 http 获取,而且我只想执行一次。