MrNew MrNew - 19 days ago 7
Javascript Question

Angular2 how to do a url query string

I have a search feature on my application which searches a list of products, which is all going okay however I want to redirect the user to another page say

www.site.com/search?keyword=perfume


I can only make it
www.site.com/search/perfume
and
www.site.com/search;keyword=perfume


Router navigate
this.router.navigate(['search', {keyword: searchVal}]);
doing this results as
www.site.com/search;keyword=perfume


Routes

const appRoutes: Routes = [
{ path: 'search', component: SearchComponent}
];


Search function:

findproduct(searchTerm: HTMLInputElement): void {
var searchVal = searchTerm.value;
this.productService.searchproduct(searchVal)
.subscribe(data => {
this.router.navigate(['search', {keyword: searchVal}]);
console.log(data)
});


}

How can I make my url to be
www.site.com/search?keyword=perfume

Answer

You should use queryParams:

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