Background:
I have recently published my angular project on namecheap hosting. Due to routing issues, I have enabled useHash = true
while exporting my app-routing.ts
file.
export const appRoutingModule = RouterModule.forRoot(routes,{ enableTracing: false, useHash: true});
Since, my routing issues resolved, however in all my URL's I got #.
Issue:
At one point in my code, I access the URL and analyze the URL, if there is already a search query parameter I append the new one with &
symbol or if there is not then I add the search query with ?
sign.
var uid = this.route.snapshot;
var searchURL = "";
alert("Checking search:: " window.location.search); // returns empty
alert("One more time:: " new URLSearchParams(location.search)); // returns empty
if (new URL(window.location.href).search == "")
{
searchURL = "?" incomingSearch;
}
else
{
searchURL = new URL(window.location.href).search "&" incomingSearch;
}
this.location.replaceState( uid.routeConfig.path searchURL);
If my url is like
http://localhost:4200/#/women?occasion=cozy
The window.location.search
returns empty
If I remove # from my URL I received the data
http://localhost:4200/women?occasion=cozy
The window.location.search
returns '?occasion=cozy'
Any help is appreciated. I have looked at this question as well but $window.location.search
gives error though I have installed jquery.
CodePudding user response:
I assume that what you want is to modify query parameters of a URL containing a hash.
As you can see, adding ?key=value
or &key=value
to the end of the URL is not the right way to add a query parameter (search parameter) to a URL, because a URL can contain a hash.
In the URL http://example.com/?a=1&b=2#foo?c=3&d=4
, the query params are {a: 1, b: 2}
, and the hash is foo?c=3&d=4
. If you want to insert a query param into a URL, you need to do it before the hash.
URL
objects make this convenient (this is from the Node.js REPL, but works in the browser as well):
> url = new URL("https://localhost/?a=1&b=2#foo")
> url.hash = "bar"
> url.href
'https://localhost/?a=1&b=2#bar'
> url.searchParams.append("c", "something")
> url.href
'https://localhost/?a=1&b=2&c=something#bar'
>
> url.searchParams
URLSearchParams { 'a' => '1', 'b' => '2', 'c' => 'something' }
> url.searchParams.get('a')
'1'
>
CodePudding user response:
In this case you should use window.location.hash to get string after # symbol. And then parse result string to key/value pairs. How to parse: Parse query string in JavaScript
function getQuery(query, key) {
var vars = query.split('&');
for (var i = 0; i < vars.length; i ) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == key) {
return decodeURIComponent(pair[1]);
}
}
return undefined;
}