Skip to content
Advertisement

How to encode a URL in an AngularJS controller

I’m having a bit of a problem trying to submit URLs that I’m building dynamically in my AngularJS controller code, and then encoding using encodeURIComponent()

Here’s a URL example built out dynamically (prior to encoding, and will not submit via Fiddler):

http://localhost:49479/api/aggr?sid=f68f52614800393fdbef22cc55a7d3d0fea10e655fff6e7573ca&kri=[CDSStress A]:[USD 10Y X -1.25],[CDSStress A]:[USD 1Y X 1.25]&aggrFunc=SUM([CDSStress A]:[USD 10Y X -1.25]),SUM([CDSStress A]:[USD 1Y X 1.25])&dim=Counterparty

Same URL, manually encoded with %20 (which does submit to API layer via Fiddler):

http://localhost:49479/api/aggr?sid=f68f52614800393fdbef22cc55a7d3d0fea10e655fff6e7573ca&kri=[CDSStress%20A]:[USD%201Y%20X%201.25],[CDSStress%20A]:[USD%201Y%20X%20-1.25]&aggrFunc=SUM([CDSStress%20A]:[USD%201Y%20X%201.25]),SUM([CDSStress%20A]:[USD%201Y%20X%20-1.25])&dim=Counterparty

However, encoding via encodeURIComponent() does not submit to my API layer via Fiddler. Here’s the coded URL:

http%3A%2F%2Flocalhost%3A49479%2Fapi%2Faggr%3Fsid%3Df68f52614800393fdbef22cc55a7d3d0fea10e655fff6e7573ca%26kri%3D%5BCDSStress%20A%5D%3A%5BUSD%201Y%20X%201.25%5D%2C%5BCDSStress%20A%5D%3A%5BUSD%201Y%20X%20-1.25%5D%26aggrFunc%3DSUM(%5BCDSStress%20A%5D%3A%5BUSD%201Y%20X%201.25%5D)%2CSUM(%5BCDSStress%20A%5D%3A%5BUSD%201Y%20X%20-1.25%5D)%26dim%3DCounterparty

and my angular controller code which builds out the URL and submit to datacontext layer :

function sendAggrRequest(kriList, aggrFunc, dim) {

        var results = [];
        var rageVars = $rootScope.rageSessionVars;
        var url = "http://" + rageVars.domainName + ":" + rageVars.port + "/api/aggr?sid=" + rageVars.sessionID +
                "&kri=" + kriList + "&aggrFunc=" + aggrFunc + "&dim=" + dim;            

        url="http://localhost:49479/api/aggr?sid=a74b9822cf5e0e75b0d8ff0c25981a573606893150348d6cad80&kri=[CDSStress%20A]:[USD%201Y%20X%201.25],[CDSStress%20A]:[USD%201Y%20X%20-1.25]&aggrFunc=SUM([CDSStress%20A]:[USD%201Y%20X%201.25]),SUM([CDSStress%20A]:[USD%201Y%20X%20-1.25])&dim=Counterparty"
        datacontext.sendAggrRequestToServer(encodeURIComponent(url)).then(function (data) {
            if (data.status == 'FAIL') {
                if (data.messages.length > 0) {
                    logErr("Error retrieving KRI list: " + data.messages[0]);
                    return;
                }
            }
            else {
                results = data.data;
            }                
        });
 }

If you can provide some advice on the best way to encode URLs, that would be great.

thank you.

Bob

Advertisement

Answer

Try

encodeURI(uri)? 

or may be you can just regex replace space with %20

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement