我的路由模块中有一个解析器
{
path: 'path1',
component: FirstComponent,
resolve: {
allOrders: DataResolver
}
}
然后在我的解析函数中有
resolve(): Observable<Array<string>> {
return this.serviceA.getAllfooNames()
.map(result=> {
/* result is an array of strings*/
return this.serviceB.getAllBarNames(result[0])
/*orders is also supposed to be an array of strings*/
.map(orders=> return orders)
});
}
}
我希望将值 orders 存储在 allOrders 键中。 我想将 orders 数组作为 ActivatedRoute 快照中的数据传递。请帮忙。
最佳答案
您可以混合使用 concatMap
和 zip
:
resolve(): Observable<Array<string>> {
return this.serviceA.getAllfooNames().pipe(
concatMap((names) =>
zip(...names.map((name) => this.serviceB.getAllBarNames(name)))
),
map((...names) =>
names.reduce((acc, curr) => acc.concat(curr), [])
)
);
}
这将在一大串字符串中返回从 serviceB 调用返回的所有字符串。
基本上,它的作用是,您调用 getAllfooNames
,使用 concatMap
等待该请求完成,该请求会返回字符串中的一堆名称。之后,您可以使用 zip
运算符获取这些内容。该运算符使用数组映射方法执行传入其中的所有可观察量,并在所有这些都完成后发出。
然后在 map 中拾取该数据,该 map 接收多个字符串数组作为参数。然后,您可以使用 reduce
将其放入一个大数组中。
关于javascript - 通过发出 http 请求来获取路由解析器的数据,以便第二个请求的结果取决于第一个请求的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53046777/