如何合并两个观测值(不同类型)的结果

时间:2018-07-21 07:20:57

标签: rxjs

假设我有以下两个发现:

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" }
//   }
// }

1 个答案:

答案 0 :(得分:1)

以下是如何使用combineLatestpipemap进行操作的示例:

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"
        }
    }
}