首页 > 解决方案 > 如何合并两个观察的结果(不同类型)

问题描述

假设我有这两个观察结果:

const thread = of({
  thread: {
    name: "Name",
    author: null
  }
})
const author = of({name:"Snoob"})

我怎样才能得到这些观察的合并结果:

const threadWithAuthor = .....;
threadWithAuthor.subscribe(it=>console.log(it))
// {
//   thread: {
//     name: "Name",
//     author: { name: "Snoob" }
//   }
// }

标签: rxjs

解决方案


这是一个如何使用combineLatestpipe和的示例map

var {of, combineLatest } = require('rxjs')
var { map } = require('rxjs/operators')

var mergeByAuthor = ([t, a]) => {
    var x = Object.assign({}, t)
    x.thread.author = a
    return x
}

var thread = of({
  thread: {
    name: 'Name',
    author: null
  }
})

var author = of({name:'Snoob'})

var threadWithAuthor = combineLatest(thread, author).pipe(
  map(mergeByAuthor)
)

threadWithAuthor.subscribe(x => console.log(JSON.stringify(x, null, 2)))

输出

{
    "thread": {
        "name": "Name",
        "author": {
            "name": "Snoob"
        }
    }
}

推荐阅读