How can I get the query params from a url say, https://www.youtube.com/watch?v=Xnjw0SBKDM0
using angular 2? I know how to get query params from the ActivatedRoute
method, but i only need to pass a string, not my current router route.
Asked
Active
Viewed 481 times
0

Alex Nelson
- 359
- 1
- 3
- 14
-
Do you mean you'd want to get the value of the "watch" parameter? – smoyer Jul 14 '17 at 18:31
-
Yes but in general, if I had say 5 parameters, how can I get a dictionary of those key value pairs? – Alex Nelson Jul 14 '17 at 18:31
-
I don't think Angular has native functionality for parsing user-defined strings into params. You may need to just manually split the URL at `?`, `&` and `=` – Kai Jul 14 '17 at 18:37
1 Answers
0
Look at this answer. This is the method you'd need.
function getJsonFromUrl(hashBased) {
var query;
if(hashBased) {
var pos = location.href.indexOf("?");
if(pos==-1) return [];
query = location.href.substr(pos+1);
} else {
query = location.search.substr(1);
}
var result = {};
query.split("&").forEach(function(part) {
if(!part) return;
part = part.split("+").join(" "); // replace every + with space, regexp-free version
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]",from);
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
}

smoyer
- 7,932
- 3
- 17
- 26
-
1
-
Oh. thats not really specific to angular. I can update my answer though. – smoyer Jul 14 '17 at 18:36
-
Updated my answer. Check out the other answer, it should do what you want. I pasted the relevant code. – smoyer Jul 14 '17 at 18:39
-