10

Im navigating after building up a queryParams object with a form:

options {
    ...
    words: (4) ["chuck", "norris", "vs", "keanu", "reeves"]
}

Then navigate with that object to update the URL's parameters:

this.router.navigate(['/search'], { queryParams: options });

The URL words param is duplicated for each entry like this:

/search?words=chuck&words=norris&words=vs&words=keanu&words=reeves

How do we pass in an array to queryParams properly?

Links: angular.io/api/router/Router#navigate alligator.io/angular/query-parameters

queryParamsHandling has no affect on this. Here is a StackBlitz repro.

4
  • One trick is to JSON stringify the data you are passing and retrieve it using JSON.parse Commented Jul 16, 2019 at 19:19
  • 3
    Whats wrong with duplication of words? It could work like this :) From en.wikipedia.org/wiki/Query_string#Structure : "While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. field1=value1&field1=value2&field2=value3)." Another benefit is that you will automatically have an array of the query parameters inside the angular router state. So you don't have to manually parse the querystring. Commented Dec 5, 2019 at 12:13
  • I personally have never seen a URL with the same param multiple times, one for each value. Commented Dec 5, 2019 at 14:04
  • What does the (4) before the array of words add to the code? I have never come across this syntax in Typescript. Commented Mar 20, 2024 at 13:19

1 Answer 1

11

You're doing it the correct way, just use params.getAll in your /search component:

words: string[];

constructor(private route: ActivatedRoute) {
}

ngOnInit() {
  this.route.queryParamMap.subscribe(params => this.words = params.getAll('words'));
}


Update: working example on stackblitz: angular-query-params-pass-array

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Gais Zaher, but I'm not trying to get a param. I'm trying to set the params after building up an object to set.
@BenRacicot so the problem is that the words param is being duplicated? If so, I don't think it's a problem, this is the correct way to pass arrays in query parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.