Angular 5应用程序有一个数据服务,它返回指定的 category
中的产品,并且's pagination. Category is specified in routes as parameter. Pagination is and query parameter. Url' s看起来像这样: /category?page=2
. (类别是变量)
Issue: 该组件订阅了 queryParams
和 paramMap
. 如果只使用了一个,那么's fine, but going from ' / category?page = 2 ' to ' / anotherCategory'触发两者,这意味着数据被拉两次(并且取决于哪个observable首先返回数据,这会引入不需要的结果) . 在这种情况下,使用 snapshot
也不起作用 .
我无法找到解决这个问题的最佳实践 .
@Component({..}}
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.queryParams.subscribe((params: Params) => {
this.currentPage = params['page'];
this.getData(this.category, this.currentPage);
});
this.route.paramMap.subscribe ((params: Params) => {
this.category = params.get('categoryName');
this.getData(this.category, this.currentPage);
});
}
注意:为了简单起见,代码稍作修改并剥离 .
2 回答
您的疑问非常符合逻辑,我们必须在这里使用这两个订阅,因为快照不会检测相同路由的参数更改 .
我们在这里可以做的是检查getData函数中的Activated路由 . 因此,如果拉取数据的参数与我们的路线不匹配,那么我们可以简单地返回 .
我们只会在两个参数都与激活的路径匹配时获取数据 . 可以通过快照检查路径中的当前参数 .
如果需要进一步澄清,请告诉我 .
谢谢
您可以使用combineLatest创建一个可在路由参数或查询参数更改时触发的observable:
combineLatest( this.route.params, this.route.queryParams ).pipe( map(([params, qparams]) => { //do your stuff here }) )