Mor*_*ror 2 rxjs angular-ui-router angular
我正在编写一个简单的 UI 应用程序,我需要调用 API 来通过产品详细信息组件中的 id 获取产品。我从路由参数获得的 ID
通常,我会这样做:
this.activatedRoute.params
.subscribe(params => {
if (params['primaryKey']) {
this.service.get(params['primaryKey'])
.subscribe(product => {
this.product = product;
});
}
});
Run Code Online (Sandbox Code Playgroud)
它工作得很好,只是这些订阅树看起来有点难看。我想使用更多 RxJS,所以它看起来像这样(控制台日志仅用于演示):
this.product$ = this.activatedRoute.params
.pipe(filter(params => {
console.log('in filter', params);
return 'primaryKey' in params;
}),
map(params => {
console.log('in map', params);
return parseInt(params.primaryKey, 10);
}),
switchMap(primaryKey => {
console.log('in switch map', primaryKey);
return this.service.get(primaryKey);
}));
Run Code Online (Sandbox Code Playgroud)
但在我最终订阅它之前它不会以这种方式工作(它甚至不会触发任何控制台日志)......为什么?
您可以使用以下方式获取路线参数:
this.route.snapshot.paramMap.get('id')
Run Code Online (Sandbox Code Playgroud)
route属于类型ActivatedRoute
constructor(
private route: ActivatedRoute,
) { }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4809 次 |
| 最近记录: |