UIService 中的 Angular BehaviourSubject 和 2 个订阅两次的组件

我有一个包含 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 获取,而且我只想执行一次。

ning419 回答:UIService 中的 Angular BehaviourSubject 和 2 个订阅两次的组件

您可能想尝试 debounceTime,如果这些更改相继发生,但这只是一种解决方法。

import { debounceTime } from 'rxjs/operators';

ngOnInit(): void {
  this.uiService.selectSelectedTechnique()
    .pipe(debounceTime(500))
    .subscribe(val => {
      // do stuff
    })
}

我宁愿专注于弄清楚为什么技术改变了两次。很明显,它可能会导致其他组件出现问题。

本文链接:https://www.f2er.com/1672.html

大家都在问