Reputation: 349
I am trying to create an application whose state is represented in the URL directly by using paramters. One of those parameters should be a selection criterion where multiple items can be selected. Changing the selection means that items get added or removed from that list in the url parameters. That means that the list from the parameters have to be known at the point where i want to change it.
The Problem is that in the case where i change the url parameters while I am subscribed to them the url doesnt change. I made i minimal example here. I can provide some code inside this question but i think the demo is sufficient.
I figured out that the problem might be that i need to subscribe to the parameters before adding them. So i tried to build some kind of caching mechanism that stores the list in a variable. If i use that variable instead of the parameters directly it kind of works. But this is some kind of workaround that creates other problems.
Moreover if i have a second parameter that is not a list and i change that one all the changes that have been made to the list parameter will be shown in the url as expected.
Feel free to ask me anythink if you dont understand my problem.
Edit1: If you check my demo there is a button. And i expect that if you click the button a parameter will be added to the url. Each time the button is clicked another parameter should be added that the url looks like this: https://angular-slnewb.stackblitz.io/?myParameter=0&myParameter=1
.
Upvotes: 1
Views: 1015
Reputation: 388
As far as I can understand, the issue in the example you've provided is that on click of button you're not really navigating to a different page. It's the same route always. When you change the routes in setParameter
method, it merges the queryParams values
public setMyUrlParameter(url: string, myParameter: string[]): void {
const customQueryParams: Params = {};
customQueryParams["myParameter"] = myParameter;
this.router.navigate([url], {
queryParams: customQueryParams,
// preserve the existing query params in the route
queryParamsHandling: "merge"
});
}
I've created a working fork here - https://stackblitz.com/edit/angular-6-routing-tn8av4
Upvotes: 0
Reputation: 2330
You can try convert the array to string.
@Injectable()
export class MyDataService {
constructor(private activatedRoute: ActivatedRoute, private router: Router) {}
public getMyUrlParameter(): Observable<string[]> {
return this.activatedRoute.queryParams.pipe(map(params => {
const myParameter = params["myParameter"];
return myParameter ? myParameter.split(',') : [];
}));
}
public setMyUrlParameter(myParameter: string[]): void {
const customQueryParams = {};
customQueryParams["myParameter"] = myParameter.toString();
this.router.navigate([], {
queryParams: customQueryParams,
// preserve the existing query params in the route
queryParamsHandling: "merge"
});
}
}
https://stackblitz.com/edit/angular-negcsk?file=src%2Fapp%2Fmy-data.service.ts
Upvotes: 1