Tag: TypeScript

2 Posts Found
 

TypeScript Function Decodes URL Parameters

Posted: 11/14/2016 5:15 PM

Angular 2 includes a Routing module that will automatically handle URL parameters that are implicitly passed in a URL.

If you're not using Angular Routing, or if you're passing additional parameters in the URL, you'll need to parse out the query string to retrieve the URL parameters.

Below is a TypeScript function that will return a Map with key/value pairs that correspond to the URL parameters passed to a web page. You can optionally pass a query string to decode, or if you pass NULL, the function will retrieve the query string from the URL of the current web page.

    // parses the query string
    parseQueryString(queryString: string): Map<string, string> {
        // if the query string is NULL
        if (queryString == null) {
            queryString = window.location.search.substring(1);
        }

        var params = new Map<string, string>();

        var queries = queryString.split("&");

        queries.forEach((indexQuery: string) => {
            var indexPair = indexQuery.split("=");

            var queryKey = decodeURIComponent(indexPair[0]);
            var queryValue = decodeURIComponent(indexPair.length > 1 ? indexPair[1] : "");

            params[queryKey] = queryValue;
        });

        return params;
    }
 

TypeScript Syntax for Custom Getters and Setters

Posted: 11/11/2016 3:56 PM

Here is the TypeScript syntax to define custom getters and setters for variables:

    private _myVar: number

    get myVar(): number {
        return this._myVar;
    }

    set myVar(myVar) {
        this._myVar = myVar;

        callSomeOtherFunction();
    }


    retrieveCurrentMyVar(): number {
        return this.myVar; // calls the getter myVar() above
    }