2016-08-08 47 views
0

I'am using angular-route。 基於this question我試圖獲取URL參數。AngularJS Typescript IRouteParamsService undefined

我收到以下錯誤: angular.js:13920 TypeError: Cannot read property 'zvar' of undefined 看來$routeParams是未定義的。

我的路由配置: angular.module('app').config(['$routeProvider', function routes($routeProvider: ng.route.IRouteProvider) { $routeProvider .when('/', { templateUrl: 'views/start.html', }) .when('/calc/:zvar?', { templateUrl: 'views/calc.html', controller: 'app.controllers.calcCtrl' }) .otherwise({ redirectTo: '/' }); } ]);

我的URL:http://localhost:64025/#/calc?zvar=test123

構造函數的訪問:

interface IRouteParams extends ng.route.IRouteParamsService { 
     zvar: string; 
    } 
export class calcCtrl implements IController { 
     static $inject: string[] = ['$routeParams']; 
     constructor(private $routeParams: IRouteParams) { 
      this.zvar = $routeParams.zvar; 
      console.log("Calc Controller: " + this.zvar); 
     } 
     zvar: string; 
    } 

完全打字稿代碼:http://codepen.io/alexmallinger/pen/qNQRGJ

編輯:添加行static $inject: string[] = ['$routeParams'];我的代碼

回答

1

您應該注入$routeParams服務。 $inject property annotation可用於此目的:

export class calcCtrl implements IController { 
    static $inject:string[] = ['$routeParams']; 
    constructor(private $routeParams: IRouteParams) { 
     ... 
    } 
} 
+0

是否註冊了控制器? –

+0

是的。 我在這裏上傳了完整的Typescript代碼:http://codepen.io/alexmallinger/pen/qNQRGJ –

+0

嘗試註冊沒有'services'數組的控制器:'angular.module('app.controllers')。controller(controller,app .controllers [className]);' –