Mat*_*man 3 javascript angularjs typescript angular-ui angular-ui-router
当将 TypeScript 与 Angular 的 ui 状态一起使用时,我可以通过 UI-Router 明确类型库提供“类型断言”。
使用它,我可以注入$state并获得类似于以下内容的代码
function myCtrl($state: ng.ui.IStateService){
    // Some code
}
这为我提供了正确的自动完成/错误报告$state。
到目前为止,一切都很好。
当我尝试访问params如下属性时
function myCtrl($state: ng.ui.IStateService){
    // Trying to access a property of $state.params
    var example = $state.params.example;
}
我收到一条错误消息:
IStateParamsService 上不存在属性“example”
因为 TypeScript 不知道这个属性,这是正确的。
定义我自己的扩展接口ng.ui.IStateService
interface IMyState extends ng.ui.IStateService{
    params: {
        example: string;
    };
}
然后将类型设置为我的界面
function myCtrl($state: IMyState){
    var example = $state.params.example;
}
这样就消除了错误。
正确的使用类型是什么$state?
我应该像我的示例中那样定义自己的界面吗?
使用 Typescript,我们确实可以轻松地扩展合同,并附带UI-Router .d.ts。
这是原始定义(UI-Router d.ts. 文件):
// a state object
interface IStateService {
    ...
    params: IStateParamsService;
    ...
// params
interface IStateParamsService {
    [key: string]: any;
}
我们可以将这些行引入到我们的自定义 .d.ts 中
declare module angular.ui
{
    export interface IStateParamsService { example?: string; }
}
现在,这将使我们能够使用$state其参数,例如:
MyMethod($state: ng.ui.IStateService)
{
    let x = this.$state.params.example;
    ...
| 归档时间: | 
 | 
| 查看次数: | 5489 次 | 
| 最近记录: |