Reputation: 5367
I am using an Observable to show/hide a component and want to use the data. I don't want to directly call the service in the child component so that I can keep that component dumb.
@Component({
selector: 'my-component',
template: `
<child-component *ngIf="this.shouldShowChildComponent$ | async" [someData$]="data$">
</child-component>
`
}) export class MyComponent implements OnInit {
shouldShowChildComponent$ = new BehaviorSubject(false);
data$: new Observable();
constructor(private someService: SomeService) {}
ngOnInit() {
this.someService.getData().subscribe(() => {
this.shouldShowChildComponent$.next(true);
}
// it looks like this is a second subscription?
this.data$ = this.someService.getData();
}
}
What happens is that it only shows the data in the child component on the second time that this.someService.getData()
emits.
I have tried using the pipe operator in conjunction with the tap operator:
this.data$ = this.someService.getData().pipe(tap(() => {
this.shouldShowChildComponent$.next(true);
}));
Upvotes: 1
Views: 56
Reputation: 5367
Ah, it seems I can use shareReplay for that:
shouldShowOtherComponent$ = new Observable(); // changed this to an Observable
data$: new Observable();
// left out for brevity
this.data$ = this.someService.getData().pipe(shareReplay(1));
this.shouldShowOtherComponent$ = this.data$.pipe(mapTo(true));
Upvotes: 1