【问题标题】:Using typescript classes for services in angular 1.4.7在 Angular 1.4.7 中为服务使用 typescript 类
【发布时间】:2015-11-18 20:54:21
【问题描述】:

我正在尝试按照这个 Ng Conf 视频将服务实现为类Angular 1.3 遇到 Angular 2.0 - Michał Gołębiowski

https://youtu.be/pai1ZdFI2dg?t=4m25s

我不断收到此错误:

TypeError: Cannot read property 'prototype' of undefined

代码如下:

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

编辑:解决方案

简单的包装类工作,现在就可以了:

.service('myService', function () {return new MyService()})

实际上,现在我想到它似乎很简单。示例视频可能使用 es6 和 Babel,而我使用的是 Typescript。 猜测,Typescript/Tracuer 的做法可能有所不同。我将在今晚晚些时候对此进行调查并发布完整的解释。

编辑:解释

Martin Vseticka 打败了我,见下文。

【问题讨论】:

    标签: angularjs typescript


    【解决方案1】:

    线

    .service('myService', [MyService])
    

    应该是

    .service('myService', MyService)
    

    编辑:我猜这个解决方案更简单:-)

    function MyService () {
      return {
          message: "service test"
        }
    }
    

    之所以有效,是因为函数在 JavaScript 中是 hoisted

    但是,下面的 TypeScript 代码

    class MyService {
      public message:string;
      constructor () {
        this.message = "service test by class";
      }
    }
    

    被转译为:

    var MyService = (function () {
        function MyService() {
            this.message = "service test by class";
        }
        return MyService;
    })();
    

    这意味着.service('myService', MyService) 无法工作,因为此时未定义MyService(即MyService = undefined)!

    【讨论】:

    • 啊,是的,这看起来很奇怪,但这只是我为示例删除的注入注释的残余。以前.service('myService', ['$http', MyService])。这似乎不是问题。
    • 吊装,应该猜到了>_
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2015-09-05
    • 2016-01-09
    • 2019-08-01
    • 1970-01-01
    相关资源
    最近更新 更多