【问题标题】:How angular2 get query-param like this "sort=field1,asc&sort=field2,desc&sort=field3,asc"angular2 如何获得这样的查询参数“sort=field1,asc&sort=field2,desc&sort=field3,asc”
【发布时间】:2016-10-25 10:39:04
【问题描述】:
我用 angular2
如果网址是这样的:
url?sort=field1,asc&sort=field2,desc
我用
getParams() {
if (this.route.snapshot.queryParams) {
console.log(this.route.snapshot.queryParams)
// it print like this : sort: "[object Object]"
console.log(typeof this.route.snapshot.queryParams['sort']); // is string
}
}
如何得到“field1,asc”和“field2,desc”形式排序:“[object Object]”
【问题讨论】:
标签:
angular
angular2-routing
queryparam
【解决方案1】:
参数始终只是字符串。没有办法解决这个问题。因此,当您尝试将对象作为参数值传递时,它只会在对象上调用Object.toString,默认为[object Object]。如果你有一个类,你可以覆盖toString。也许像
class Sort {
constructor(public field: string, public order: string) {}
static parse(value: string): Sort {
const split = value.split(',');
return new Sort(split[0], split[1]);
}
toString() {
return `${this.field},${this.order}`;
}
}
然后,当您添加查询参数时,只需这样做
this.router.navigate(['...'], { queryParams: { sort: new Sort('field1', 'desc') }});
Angular 将在创建查询参数时调用 Sort 实例上的 toString。然后在接收端,只需拨打Sort.parse(value)。