Angularjs + Typescript, How to use $routeParams with IRouteParamsService

天大地大妈咪最大 提交于 2019-12-06 20:33:44

问题


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?


回答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.




回答2:


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



来源:https://stackoverflow.com/questions/24315893/angularjs-typescript-how-to-use-routeparams-with-irouteparamsservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!