2014-06-19 10 views
9

Sto utilizzando $ routeParams per inserire proprietà dall'URI e impostare su loro le variabili locali.

Quando uso typescripts digitando il tipo di $ routeParams, non posso accedere a $ routeParams.

Come accedere alle proprietà in $ 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"); 
    } 

}

Il codice ng.route.IRouteParamsService è:

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

Questo ha un errore: la proprietà 'proprietà1 non esiste sul tipo di ng.route.IRouteParamsService'

Se cambio il tipo di $ routeParams su: any allora imposta correttamente la proprietà1. Come posso mantenere la rigida tipizzazione di Typescript mentre sto ancora acquisendo le proprietà in $ routeParams?

risposta

23

Capito. È necessario dichiarare un'interfaccia che utilizza IRouteParamsService e specifica le proprietà che si desidera utilizzare.

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"); 
    } 
} 

notare il cambiamento nel contructor del controller.

2

È possibile utilizzare $routeParams['property1'] anziché $routeParams.property1

Problemi correlati