下面,我有向两个API端点发出请求的代码。我正在寻找一种onNext()
功能只能触发一次的方法。现在,如果您运行下面的代码logs
fire 1
,则可以看到它fire 2
。我只希望它触发一次,并且将两者中的内容都放在一个数组中。
import axios from 'axios'
import Rx from 'rx'
import assert from 'assert'
describe('rx axios', () => {
it('should make http request to api', (done) => {
let array = ['http://jsonplaceholder.typicode.com/users/1', 'http://jsonplaceholder.typicode.com/users/2']
function httpGet(url) {
return axios.get(url)
}
let source = Rx.Observable
.fromArray(array)
.concatMap(httpGet)
let count = 0
let subscription = source.subscribe(
function (responses) {
console.log(`fire ${count}`)
count++
// assert.equal(responses[0].data.name, 'Leanne Graham')
// assert.equal(responses[1].data.name, 'Ervin Howell')
},
function (err) {
done(err)
},
function () {
done()
})
})
})
您应该能够使用toArray
。因此,例如:
let source = Rx.Observable
.fromArray(array)
.concatMap(httpGet)
.toArray()
我相信toArray
RxJs v5也可以使用它,但是如果您使用的是该版本,请不要相信我并检查它。我正在使用v4。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句