-1

I use angular2

if the url is like this :

url?sort=field1,asc&sort=field2,desc

I use

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
    }
}

How to get "field1,asc" and "field2,desc" form sort: "[object Object]"

4

1 回答 1

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 将在创建查询参数时调用toString实例Sort。然后在接收方,只需调用Sort.parse(value).

于 2016-10-25T11:08:32.867 回答