我正在编写一个简单的 UI 应用程序,我需要调用 API 以在产品详细信息组件中通过 ID 获取产品。我从路由参数中获取的 ID
通常,我会这样做:
this.activatedRoute.params
.subscribe(params => {
if (params['primaryKey']) {
this.service.get(params['primaryKey'])
.subscribe(product => {
this.product = product;
});
}
});
它工作正常,只是这些订阅树看起来有点丑。我想使用更多 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);
}));
但在我最后订阅它之前它不会以这种方式工作(它甚至不会触发任何控制台日志)...为什么?
最佳答案
没有订阅的解决方案
您可以通过以下方式获取路由的参数:
this.route.snapshot.paramMap.get('id')
route
是类型 ActivatedRoute
constructor(
private route: ActivatedRoute,
) { }
关于angular - 使用 Angular 路由参数而不订阅它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56977235/