再次使用 Observable 的值和 return Observable
Use the value of an Observable and return the Observable again
我正在使用一个 Observable 来 show/hide 一个组件并且想要使用数据。我不想直接调用子组件中的服务,这样我就可以让该组件保持哑巴状态。
@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();
}
}
发生的情况是它仅在 this.someService.getData()
第二次发出时显示子组件中的数据。
我试过将管道运算符与水龙头运算符结合使用:
this.data$ = this.someService.getData().pipe(tap(() => {
this.shouldShowChildComponent$.next(true);
}));
啊,看来我可以用 shareReplay 了:
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));
我正在使用一个 Observable 来 show/hide 一个组件并且想要使用数据。我不想直接调用子组件中的服务,这样我就可以让该组件保持哑巴状态。
@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();
}
}
发生的情况是它仅在 this.someService.getData()
第二次发出时显示子组件中的数据。
我试过将管道运算符与水龙头运算符结合使用:
this.data$ = this.someService.getData().pipe(tap(() => {
this.shouldShowChildComponent$.next(true);
}));
啊,看来我可以用 shareReplay 了:
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));