Angularjs + Typescript,如何在 IRouteParamsService 中使用 $routeParams [英] Angularjs + Typescript, How to use $routeParams with IRouteParamsService

查看:33
本文介绍了Angularjs + Typescript,如何在 IRouteParamsService 中使用 $routeParams的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 $routeParams 从 URI 中提取属性并将本地变量设置为它们.

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

当我使用打字稿输入设置 $routeParams 的类型时,我无法访问 $routeParams.

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

如何访问 $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");
    }

}

ng.route.IRouteParamsService 代码是:

The ng.route.IRouteParamsService code is:

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

这里有一个错误:属性property1 在 ng.route.IRouteParamsService 类型上不存在"

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

如果我将 $routeParams 的类型更改为 :any,那么它会正确设置 property1.如何在仍然访问 $routeParams 中的属性的同时保持 Typescript 的严格类型?

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?

推荐答案

想通了.您需要声明一个使用 IRouteParamsService 的接口并指定您要使用的属性.

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.

这篇关于Angularjs + Typescript,如何在 IRouteParamsService 中使用 $routeParams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆