'Use the value of an Observable and return the Observable again
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);
}));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
