角4:无法更新URL的查询字符串
我有一个搜索表单与几个过滤器。它们分布在文本输入,复选框和收音机按钮中。每个与这些过滤器的交互都必须更新URL的查询字符串。角4:无法更新URL的查询字符串
我还可以有以下情况:
http://example.com/search?myFilter=1&myFilter=2&myFilter=3
哪个将被转换为一个这样的数组:myFilter = [ '1', '2', '3']。
更新的查询字符串的代码如下:
this.router.navigate([], {queryParams: myNewQueryString, relativeTo: this.routerActive});
其中“this.router”是ActivatedRoute的一个实例,并且“myNewQueryString”是含有查询字符串的新参数的对象。这段代码做的是将路由重定向到更新查询字符串。
在使用新过滤器更新查询字符串之前,我需要确保不会丢失已经是URL一部分的其他过滤器。所以我需要做的是读取查询字符串,进行我需要的更改,然后将值返回给URL。
要读取查询字符串我用这个代码:
const currentQueryString: any = this.routerActive.snapshot.queryParams;
,从我可以开始做我需要改变,继续前进,但问题是,试图改变这个对象的属性,角给我下面的错误:
TypeError: Cannot assign to read only property 'parameter' of object
这个错误是因为属性:
this.routerActive.snapshot.queryParams
都是只读的,所以我不能直接对它们进行修改。我需要做的就是将属性复制到一个新的对象,像这样:
const newQueryString: any = {};
for (const key in currentQueryString) {
if (currentQueryString.hasOwnProperty(key)) {
newQueryString[key] = currentQueryString[key];
}
}
现在我有当前查询字符串,我可以进行修改,它的副本。问题是当我在一个数组中有多个值时,查询字符串不会被更新。它仅更新第一个值。
这是一个错误?有没有更好的方法呢?
完整的代码我的工作是这样的:
//query is an object like: { 'param' : 'value' }
updateQueryString(query: any): void {
const currentQueryString: any = this.routerActive.snapshot.queryParams;
const newQueryString: any = {};
//Copy the current query string
for (const key in currentQueryString) {
if (currentQueryString.hasOwnProperty(key)) {
newQueryString[key] = currentQueryString[key];
}
}
// Apply the new filter to the copy of the query string
for (const key in query) {
if (query.hasOwnProperty(key)) {
if (newQueryString[key] instanceof Array) {
newQueryString[key].push(query[key]);
} else {
const filter = [];
filter.push(query[key]);
newQueryString[key] = filter;
}
}
}
this.router.navigate([], {queryParams: newQueryString, relativeTo: this.routerActive});
this.search(newQueryString);
}
有迹象表明,我需要这个功能做其他验证,但现在我只想做更改URL。我将每个参数都视为一个Array,因为我可以在这个问题的开头提到这个场景。
看来问题在于从当前查询字符串复制到新字符串的过程中。出于某种原因,我们需要提供一个新的数组实例,以便Angular能够理解变化并将其应用于URL。
为了提供这种新的实例,我们可以改变:
此:
newQueryString[key] = currentQueryString[key];
进入这个:
newQueryString[key] = Array.from(currentQueryString[key]);
通过创建数组问题得到解决的新实例,我需要的更改现在反映在URL上。
还有几个其他验证需要使此读取复制更改应用查询字符串进程好,但我不认为这些细节是相当相关的一旦问题是如何处理由实例提供的实例ActivatedRoute。
如果有人在这样的问题上磕磕绊绊,显然只是与对象的新实例一起工作,而且你很好走。