Angularjs + Typescript, How to use $routeParams with IRouteParamsService

All we need is an easy explanation of the problem, so here it is.

I am using the $routeParams to pull in properties from the URI and set local vars to them.

When I use typescripts typing to set the type of $routeParams, I can no loger access the $routeParams.

How can I access the properties in the $routeParams?

class Controller{
    constructor($routeParams: ng.route.IRouteParamsService, private $location: ng.ILocationService)
        this.propetry1 = this.getProperty1($routeParams.property1);
    }

    property1: string;

    getProperty1(input: string):string{
        return (input || "Not present");
    }

}

The ng.route.IRouteParamsService code is:

interface IRouteParamsService {
    [key: string]: any;
}

This has a error: the property ‘property1 does not exist on type of ng.route.IRouteParamsService’

If I change the type of $routeParams to :any then it correctly sets property1.
How can I keep the strict typing of Typescript while still acessing the properties in $routeParams?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Figured it out. You need to declare an Interface that uses IRouteParamsService and specifies the properties you want to use.

 interface IRouteParams extends ng.route.IRouteParamsService {
    property1:string;
 }

 class Controller{
    constructor($routeParams: IRouteParams, private $location: ng.ILocationService)
        this.propetry1 = this.getProperty1($routeParams.property1);
    }

    property1: string;

    getProperty1(input: string):string{
        return (input || "Not present");
    }
}  

Notice the change in the constructor of the controller.

Method 2

You can use $routeParams['property1'] instead of $routeParams.property1

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply