[英]Chain observables to load dependent datas
I'm loading an employee in my resolver.我正在我的解析器中加载一名员工。 This employee returns a list of town's ids.
该员工返回城镇 ID 列表。 I want to load all the towns from this town's id list in the same resolver.
我想在同一个解析器中加载这个城镇的 id 列表中的所有城镇。 But I don't want to return the list of town, I want to return the employee.
但是我不想返回城镇列表,我想返回员工。 The loaded town will be added in a cache service to be used later.
加载的城镇将被添加到缓存服务中以供稍后使用。 Here is my code
这是我的代码
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
return this.employeeService.getEmployee(route.params['id'])
.pipe(
map(employee => {
const townsObservables = [];
employee['town_list'].forEach((townId) => {
townsObservables.push(this.townService.getTown(townId));
});
return forkJoin(townsObservables).pipe(
map(town => {
this.townCache.addTown(town);
return employee;
})
);
})
);
}
Problem : the forkJoin is never executed and the route snapshot data in my component return an Observalbe instead of a employee.问题:永远不会执行 forkJoin 并且我组件中的路由快照数据返回 Observalbe 而不是员工。
route.snapshot.data['employee'] // returns Observable {_isScalar: false, source: Observable, operator: MapOperator}
The employeeService is working well without all the code in pipe, this code works like expected (I can get my employee in my snapshot data):没有管道中的所有代码,employeeService 运行良好,此代码按预期工作(我可以在我的快照数据中获取我的员工):
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
return this.employeeService.getEmployee(route.params['id']);
}
Question : what is the correct way to load related datas without returning them in a resolver?问题:加载相关数据而不在解析器中返回它们的正确方法是什么? I was about to try to use two separates resolvers but the resolvers cannot be chained (there is no way to tell resolver B to use datas from resolver A).
我正要尝试使用两个单独的解析器,但无法链接解析器(无法告诉解析器 B 使用来自解析器 A 的数据)。
I'm using Angular 6 with RXJS ^6.2.1.我将 Angular 6 与 RXJS ^6.2.1 一起使用。
You should use mergeMap
if you want to subscribe forkJoin
.您应该使用
mergeMap
如果你想订阅forkJoin
。
return this.employeeService.getEmployee(route.params['id'])
.pipe(
mergeMap(employee => { // <-- HERE changed to mergeMap
const townsObservables = [];
employee['town_list'].forEach((townId) => {
townsObservables.push(this.townService.getTown(townId));
});
return forkJoin(townsObservables).pipe(
map(town => {
this.townCache.addTown(town);
return employee;
})
);
})
);
Main difference between map
and mergeMap
: map
和mergeMap
之间的主要区别:
map(val => of(val))
-> results in Observable<Observable<val>>
map(val => of(val))
-> 结果是Observable<Observable<val>>
mergeMap(val => of(val))
-> results in Observable<val>
mergeMap(val => of(val))
-> 结果是Observable<val>
It is equivalent to .pipe(map(val => of(val)), mergeAll())
它相当于
.pipe(map(val => of(val)), mergeAll())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.