我是RxJ的新手。我不知道怎么做这件事。我的主数据中有大量嵌套的http请求。我想获取所有的http请求,并将它们组合到我的主流中。
我的示例主流数据如下:
[
{
id: '123',
name: 'nameVal1',
salary: [
{ href: 'http://example.com/salary/1' },
{ href: 'http://example.com/salary/2' }
],
address: {
href: 'http:/example.com/address'
}
},
{
id: '456',
name: 'nameVal2',
salary: {
href: 'http://example.com/salary/1'
},
address: {
href: 'http:/example.com/address'
}
}
];salary对象示例:
{
salary: '1000€',
month: 2
}示例address对象:
{
country: 'UK',
city: 'London',
postalCode: '123'
}我的主流是像上面这样的对象数组,在获取主流之后,我想获得所有嵌套的数据,并像这样将它们组合成所有的主流:
[
{
id: '123',
name: 'nameVal1',
salary: [
{
salary: '1000€',
month: 2
},
{
salary: '500€',
month: 3
}
],
address: {
country: 'UK',
city: 'London',
postalCode: '123'
}
},
{
id: '456',
name: 'nameVal2',
salary: [
{
salary: '2000€',
month: 3
}
],
address: {
country: 'UK',
city: 'London',
postalCode: '456'
}
}
];
this.service.mainHttpReq().pipe(
map(users => {
users.salary.forEach(salaryItem => {
return fetch(salaryItem.href);
});
})
).subscribe(usersData => {
console.log('Users Data :', usersData);
});发布于 2021-01-26 19:08:02
使用forkJoin并行获取数据。
mainStream.pipe(
// fetch data for every person
switchMap(persons => forkJoin(
persons.map(person => getPersonData(person))
))
);
// get data for a single person
function getPersonData(person): Observable<any> {
// the salary data as an observable
const salaryData = forkJoin(person.salary.map(({ href }) => getSalaryData(href));
// the address data as an observable
const addressData = getAddressData(person.address.href);
// combine salary and address data
return forkJoin(salaryData, addressData).pipe(
// map salary and address data to a person object with this data
map(([ salary, address ]) => ({ ...person, salary, address }))
);
}发布于 2021-01-26 19:02:14
正确的解决方案可能取决于您是否希望并发获取薪水,但您可以这样做,例如:
this.service.mainHttpReq().pipe(
concatAll(), // Unwrap the users array into individual `next` values representing each user.
concatMap(user => // Process users in sequnece one by one.
forkJoin( // Fetch all salaries and address for this user in parallel.
forkJoin(user.salary.map(salary => fetch(salaryItem.href))),
fetch(user.address),
).pipe(
map(([salaries, address]) => { // Update the original user object.
user.salary = salaries;
user.address = address;
return user;
}),
),
),
toArray(), // Collect into a one array of users.
).subscribe(...);我没有测试上面的代码,但我希望你能理解它是如何工作的。
https://stackoverflow.com/questions/65899721
复制相似问题