Angularjs + Typescript, How to use $routeParams with IRouteParamsService
Asked Answered
C

2

13

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?

Cycle answered 19/6, 2014 at 20:43 Comment(0)
C
25

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.

Cycle answered 20/6, 2014 at 16:24 Comment(0)
T
2

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

Tokyo answered 2/3, 2016 at 13:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.