[英]Using typescript classes for services in angular 1.4.7
I'm trying to implement services as classes as per this Ng Conf video Angular 1.3 meets Angular 2.0 - Michał Gołębiowski : 我正在尝试按照此Ng Conf视频Angular 1.3满足Angular 2.0的方式将服务实现为类-MichałGołębiowski :
https://youtu.be/pai1ZdFI2dg?t=4m25s 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 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.
示例视频使用的是es6或Babel,而我使用的是Typescript。 At a guess , Typescript/Tracuer is probably doing things differently.
猜想 ,Typescript / Tracuer可能在做事上有所不同。 I will look into this later tonight and post a full explanation.
我将在今晚晚些时候对此进行调查并发表完整的解释。
EDIT: Explanation 编辑:解释
Martin Vseticka beat me to it, see below. Martin Vseticka击败了我,请参阅下文。
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. 之所以起作用,是因为函数是用JavaScript 悬挂的。
However, the following TypeScript code 但是,以下TypeScript代码
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! 这意味着
.service('myService', MyService)
因为不能工作MyService
没有定义(即, MyService = undefined
在该点)!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.