将它们与 zip 或 combineLatest 结合起来
在组件中:
//now filtering out falsey values for getData
// make it .filter(v => v !== undefined) to ignore undefined specifically
dataOne$ = getData(1).filter(v => v);
dataTwo$ = getData(2).filter(v => v);
combined$ = Observable.zip(dataOne$, dataTwo$).do(e => console.log('do whatever you want here');
或者:
combined$ = Observable.combineLatest(dataOne$, dataTwo$).do(e => console.log('do whatever you want here');
在模板中:
<parent-component *ngIf="combined$ | async as combined">
<child-component [input]="combined[0]"></child-component>
<child-component [input]="combined[1]"></child-component>
</parent-component>
或者可能:
<parent-component >
<child-component *ngFor="let input of combined$ | async" [input]="input"></child-component>
</parent-component>
第一个将使父子节点仅在组合至少解析一次时才实例化。
第二个将让父项立即实例化,但子项在两个项目都解决一次之前不会实例化。
第一个选项有一个微妙的好处,如果您使用 onpush 更改检测,父组件的更改检测将在每次异步更新中订阅它的 observable 时触发,但在第二种情况下不会触发,尽管无论如何,do 运算符都会触发。
只有两个 observables 更新时,zip 才会触发,并成对地为您提供值
combineLatest 将在其中一个触发时触发(在两者都触发一次之后)并为您提供另一个的最新值。