且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

合并两个可观察对象,单个输出

更新时间:2023-10-06 13:43:28

合并可观察对象意味着,由两个可观察对象发出的项目将由新合并的可观察对象(分别参见 zip运算符如下:

Merging observables means that items emitted by both observable will be emitted successively and separately by the new merged observable, cf this page. If your observables emit just one item each and you want the merge the items by concatenating the arrays, you could use the zip operator as follows:

zip(observable, this.observable)
  .pipe(map(x => x[0].concat(x[1])))
  .subscribe(data => console.log('merge', data))

更精确地讲, zip(obsa,obsb)创建了一个新的可观察对象,它监听obsa和obsb,并且在收到obsa的itema和obsb的itemb之后,会发出 x = [itema,itemb] .在您的情况下, x [0] = itema x [1] = itemb 是数组,而(x => x [0] .concat(x [1]))连接这两个数组.请注意,如果obsa和obsb发出多个数组,则在发出新的 [itema,itemb] 之前,压缩的可观察对象将始终等待obsa中的一项和obsb中的一项.对于concat()方法,请参见此页面.

More precisely zip(obsa, obsb) creates a new observable that listens to obsa and obsb, and after receiving itema from obsa and itemb from obsb emits the item x=[itema, itemb]. In your case x[0]=itema, x[1]=itemb are arrays and (x => x[0].concat(x[1])) concatenates these two arrays. Note that if obsa and obsb emit more than one array, the zipped observable will always wait to have one item from obsa and one from obsb before emitting a new [itema, itemb]. For the concat() method, cf this page.

别忘了从'rxjs'导入{zip} 从'rxjs/operators'导入{map} .