0

I´am using angular-route. Based on this question I´ve tried to get the URL parameter.

I get the following error: angular.js:13920 TypeError: Cannot read property 'zvar' of undefined It seems that $routeParams is undefined.

My routing config: 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: '/' }); } ]);

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

The access in the constructor:

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

Full Typescript code: http://codepen.io/alexmallinger/pen/qNQRGJ

EDIT: Added the line static $inject: string[] = ['$routeParams']; to my code

Community
  • 1
  • 1
alexander-fire
  • 1,082
  • 4
  • 27
  • 52

1 Answers1

1

You should inject $routeParams service. $inject property annotation can be used for this:

export class calcCtrl implements IController {
    static $inject:string[] = ['$routeParams'];
    constructor(private $routeParams: IRouteParams) {
        ...
    }
}
Aleksey L.
  • 35,047
  • 10
  • 74
  • 84