I'm trying to implement services as classes as per this Ng Conf video Angular 1.3 meets Angular 2.0 - Michał Gołębiowski :
https://youtu.be/pai1ZdFI2dg?t=4m25s
I keep getting this error:
TypeError: Cannot read property 'prototype' of undefined
Code below:
var angular = window['angular'];
angular
.module('myApp', [])
.service('myService', [MyService])
.directive('test', function (myService) {
return {
restricts: 'E',
template: 'Directive output: {{ctrl.message}}',
controllerAs: 'ctrl',
controller: function () {
this.message = myService.message;
}
}
});
/*
// Works
function MyService () {
return {
message: "service test"
}
}
*/
// Does not work
class MyService {
public message:string;
constructor () {
this.message = "service test by class";
}
}
http://codepen.io/AshCoolman/pen/PPLONm?editors=001
EDIT: Solution
Simple wrapping the class works, and that will do for now:
.service('myService', function () {return new MyService()})
Actually it seems quite straight forward now I think of it. The example video is using es6 perhaps with Babel, while I'm using Typescript. At a guess , Typescript/Tracuer is probably doing things differently. I will look into this later tonight and post a full explanation.
EDIT: Explanation
Martin Vseticka beat me to it, see below.
The line
.service('myService', [MyService])
should be
.service('myService', MyService)
Edit: The solution is more simple I guess :-) The approach with
function MyService () {
return {
message: "service test"
}
}
works because functions are hoisted in JavaScript.
However, the following TypeScript code
class MyService {
public message:string;
constructor () {
this.message = "service test by class";
}
}
is transpiled to:
var MyService = (function () {
function MyService() {
this.message = "service test by class";
}
return MyService;
})();
which means that .service('myService', MyService)
cannot work because MyService
is not defined (ie MyService = undefined
) at that point!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.