简体   繁体   English

rxjs将来自2个不同可观察对象的2个对象组合在一起

[英]rxjs combining 2 objects together from 2 different observables

I have 2 observables that are listening for a database call respectively. 我有2个可观察对象,分别在监听数据库调用。 I need to merge the 2 arrays together. 我需要将2个数组合并在一起。 If I have the following arrays 如果我有以下数组

array1 = [{id: 1, content1: "string"}, {id: 2, content2: "string"}, {id: 3, content3: "string"}]
array2 = [{id: 1, contentX: "string"}, {id: 2, contentY: "string"}, {id: 3, contentZ: "string"}]

I want to merge them together so that I get a single observable array like this: 我想将它们合并在一起,这样就得到了一个可观察的数组,如下所示:

[{id:1, content1:"string", contentX:"string"}, {id:2, content2:"string", contentY:"string"}, {id:3, content3:"string", contentZ:"string"}]

I have some code but I'm really confused on how to proceed, I can't seem to find the right operators or chain them properly, does anyone have a good explanation on how to proceed? 我有一些代码,但是我对如何继续感到很困惑,我似乎找不到合适的运算符或正确地链接它们,有人对如何进行有很好的解释吗? This is what I have so far, but literally don't know how to go on. 到目前为止,这就是我所拥有的,但实际上不知道如何继续。

    const observable1 = getDataFromDb1();
    const observable2= getDataFromDb2();

    observable1 .pipe(
        combineLatest(observable2),
        flatMap(x => {
            //what to do here???
        })
    ).subscribe(
        (value)=>{
            console.log(value);
        }
    )

Thanks for your time 谢谢你的时间

I'm taking a wild guess here, and assume that both source-observables emit their values in one big chunk. 我在这里进行了一个疯狂的猜测,并假设两个源可观察对象都在一个大块中发出它们的值。 If that's the case, you simply want to map both emissions to a custom merged one (otherwise please leave a comment). 在这种情况下,您只想将两种排放都map到一个自定义的合并排放中(否则请发表评论)。 Eg: 例如:

 const { of, combineLatest } = rxjs; const { map } = rxjs.operators; // simple merge-by-id const mergeById = ([t, s]) => t.map(p => Object.assign({}, p, s.find(q => p.id === q.id))); const db1$ = of([ {id: 1, content1: 'string'}, {id: 2, content2: 'string'}, {id: 3, content3: 'string'}, ]); const db2$ = of([ {id: 1, contentX: 'string'}, {id: 2, contentY: 'string'}, {id: 3, contentZ: 'string'}, ]); const all$ = combineLatest(db1$, db2$).pipe( map(mergeById) ); all$.subscribe(console.log); 
 <script src="https://unpkg.com/rxjs@6.2.1/bundles/rxjs.umd.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM