【发布时间】:2019-05-15 23:06:19
【问题描述】:
为了学习,我正在尝试在例如 forkjoin 之后保留流。但我想用管道(以一种优雅的方式)来做。不只是恢复数组,然后再重写一个from(array).subscribe。
我尝试在管道内做一个 from,但这不起作用。另外我想知道(作为奖励问题)在管道中(在这种情况下是第一个管道,因为我想会有 2 个管道)在 forkJoin 数组之前修改每个 mock_post 调用结果的理想方式是什么被退回。
只是我创建的一个小模拟函数,用于模拟 2 秒后的虚拟 api 返回值。
private mock_post(url: string): Observable<object> {
return from(timer(2000)).pipe(
map(result => {
return {id: 2, name: 'mock', source: url};
})
);
}
使用 ForkJoin 的第一个测试用例(使用上述函数)
const operations = [];
operations.push(this.mock_post('/api/test/'));
operations.push(this.mock_post('/api/test/2'));
operations.push(this.mock_post('/api/test/3'));
forkJoin(operations).pipe(
)
.subscribe(
(next) => {
console.log(next);
}
);
concatAll() + toArray() 的第二个测试用例。
const obs: Observable<any> = from(operations);
obs.pipe(
map(result => {
// I want to modify the result here, and add something to the object or modify a property (for example)
console.log(`result-> `, result); // This is(obviously, returning an observable, but how do I get the final value here?)
result.name = 'mock_modified';
return result;
}),
concatAll(),
toArray()
).subscribe(
(next) => {
console.log(`-> NEXT`, next);
},
(error) => {
console.log(`* ERROR`, error);
},
() => {
console.log('=) COMPLETE');
}
);
如果有人能在这里散发出一些光芒,那就太好了。希望我的解释正确。
【问题讨论】:
标签: typescript rxjs