angular - Angular 7:如何在订阅中转换查询参数?
问题描述
我想在订阅中将查询参数转换为整数,但由于某种原因,将查询参数转换为整数(或任何其他类型)之后的代码会导致代码停止执行。
combineLatest(params, queryParams, (params, qparams) => ({ params, qparams }))
.subscribe(allParams => {
this.item.color = allParams.qparams['color'] || allParams.params['color'] || ''; //this line must be above
this.item.price = parseInt(allParams.qparams['price']) || 0; //this line also
this.items.features = allParams.qparams['features'].map(feature => parseInt(feature));
});
地图(或我尝试过的任何其他转换)工作,但它下面的行不执行。我不知道问题是否与
- 使用数组(
features
是一个数组); - 在异步中调用同步函数(map);
- 完全不同的东西。
我很感激任何关于正在发生的事情的建议。
解决方案
我不确定combineLatest
在您的场景中使用 是不是多余的。我什至会跳起来说这是你的问题,因为combineLatest
将等待它提供的所有可观察对象发出初始值(从你的代码来看,这似乎不会发生)。我会做这样的事情:
constructor(route: ActivatedRoute) {}
ngOnInit(): void {
this.item.color = '';
this.item.price = 0;
this.item.features = [];
this.route.queryParams.subscribe(queryParams => {
this.item.color = queryParams['color'] || '';
this.item.price = queryParams['price'] || 0;
this.item.features = queryParams['features'].map(feature => parseInt(feature));
});
// ...Do the same with this.route.params
}
如果你想使用combineLatest
但不想被动地等待初始值,你可以用管道传递一个.pipe(startWith(null))
:
combineLatest(params.pipe(startWith(null)), queryParams.pipe(startWith(null)), (params, qparams) => ({ params, qparams })) ....
或者...您可以使用zip而不是combineLatest
.
推荐阅读
- tensorflow - 在 Tensorflow 中训练多个模型时如何避免过多的内存使用
- r - 如何用最接近的两个值的平均值替换 NA
- c# - 使用 FluentFTP 通过 TLS/SSL 向/从 FTP 服务器传输时,“身份验证失败,因为远程方已关闭传输流”
- python - 为什么当我们为列表列表中的每个列表列出列表的所有元素时,我们需要在 for in 子句中使用特定的顺序?
- kubernetes - 意外覆盖了默认的集群管理员角色
- jsf - 浏览器不解释 JSF 标记
- java - 在这种情况下,如何根据单击的单选按钮检索数值?
- python - Python ortools 安排每周最大/最小工作时间
- html - Bootstrap 导航栏垂直分隔线
- javascript - pouchDB 查询在导出的异步函数中使用时返回空对象