聆听同一个可观察的两个分量

时间:2020-04-25 21:05:32

标签: angular

我有两个(主要,次要)组件和一个服务。全部在同一模块上

在我的服务中,我有以下代码:

private showThisSource = new BehaviorSubject<({ show: boolean })>({} as any);
currentThis = this.showThisSource.asObservable();

changeThis(data: { show: boolean }) {
      this.showThisSource.next(data);
}

在我的主要组件中,我有以下代码:

showThis(){
  this.theServiceAbove.changeThis({show:true})
}

在我的其他组件(子组件)中,我有以下代码:

currentThis$ = this.theServiceAbove.currentThis
   .pipe(
         tap(data=>
              console.log('Display to log')
            ) 
        );

vm$ = combineLatest(
   this.currentThis$
  ).pipe(
         map(([currentThis]) =>
           ({ currentThis}))
        )

--template---

<div>
   <ng-container *ngIf="(vm$ | async) as vm">
   <ng-container>
</div>


现在的问题是,即使我在主组件上调用了changeThis子组件的currentThis $也没有发生,我怎么知道呢?因为console.log('Display to log');没有出现。

我不知道我在这里想念什么。

1 个答案:

答案 0 :(得分:0)

您的代码中存在语法错误。我将其放入Stackblitz中并进行了必要的更改,并显示了console.log并将其放入视图中。

.pipe(
   tap(data=>
       console.log('Display to log') // Removed semi-colon from this line
   ) 
);

https://stackblitz.com/edit/angular-ynvtao