Route with array parameter in Angular 4

Viewed 6282

I'm currently trying to solve problem with routing in Angular 4. I want the URL to contain array of parameters, so it looks like this: /#/WF001A;operationIds=146469,146470. This URL was generated by Angular using [routerLink]. Parameters needs to be accessible from component (that shouldn't be a problem, I guess).

The problem is - I don't know how to create a route for it. What I tried:

  • {path: 'WF001A/:operationIds', component: WF001AComponent}
  • {path: 'WF001A/:operationIds[]', component: WF001AComponent}
  • {path: 'WF001A:operationIds[]', component: WF001AComponent}
  • {path: 'WF001A;:operationIds[]', component: WF001AComponent}

Edit: This is how the link is generated:

<a href="#" [routerLink]="['/WF001A', {operationIds:[146469, 146470]}]">test</a>

Edit 2: Component class:

export class WF001AComponent implements OnInit {
    public title = 'WF001A';

    public constructor (private WF001AService: WF001AService, private route: ActivatedRoute) {}

    public ngOnInit(): void {
        this.route.paramMap.subscribe(params => {
            // This is never executed, for route is not recognized
            let myArray=params.getAll('operationIds');
            console.log(myArray);
        });
    }
}
1 Answers

I assume you have the ActivatedRoute object in your component, something like:

constructor(
    ...,
    private route: ActivatedRoute) { }

And I assume that WF001A is the parameter name, so you can do something like:

this.route.paramMap.subscribe(params => {
  let i=0;
  let myArray=params.getAll('operationIds');
}

You can find more information about the optional parameters in the official documentation

Related