Angular2 - 在不同文件中拆分应用程序时出现引用错误

Angular2 - Reference error when splitting application in different files

我正在尝试模块化 Angular 2 应用程序,将服务放在不同的文件中:

app.ts

/// <reference path="typings/angular2/angular2.d.ts" />
/// <reference path="./services.ts" />

import {Component, View, bootstrap, NgFor} from 'angular2/angular2';

@Component({
  selector: 'my-app',
  appInjector: [Service.TechnologiesService]
})
@View({
  templateUrl: 'index-angular',
  directives:[NgFor]
})

class MyAppComponent {
  name: string;
  technologies: Array<string>;

  constructor(technologiesService: Service.TechnologiesService) {
    this.name = 'DopAngular';
    this.technologies = technologiesService.technologies;
  }
}

bootstrap(MyAppComponent);

services.ts

module Service{
  export class TechnologiesService {
    technologies: Array<string>;
    constructor() {
      this.technologies = ['Angular 2 Developer Preview', 'Express', 'Jade', 'Gulp', 'Material Design Lite', 'Polymer', 'Sass', 'Karma', 'Mocha', 'Should', 'npm', 'Bower'];
    }
  }
}

这些文件编译成js没有错误,但是当运行浏览器中的应用程序时,我得到:

Uncaught ReferenceError: Service is not defined

知道如何解决这个问题吗?

我相信引用语句只是向 TS 编译器提供类型信息,但不会包含任何代码。因此它可能会在 IDE 中自动完成并编译,但它不会在打字稿编译器生成的 .js 中生成任何内容。因此,您需要导入您的服务,例如:

import {TechnologiesService} from 'services';

/// <reference path="./services.ts" /> 允许编译器查看引用文件的类型信息,但不会导致目标中的任何代码成为 generated/included。 (此功能主要为 external/ambient 个库设计。)

要从您自己的代码中引用其他 TS 文件,您应该使用 import {...} from 'file'; 语法(参见 handbook),例如

import {Service} from 'services'

您还需要在 TS 编译器配置和浏览器中配置模块加载器(SystemJS 或 requireJS)。

或者,您可以通过在 app.ts 之前的 <script> 标记中包含 services.ts 的编译版本来进行不可扩展的修改,并保持代码不变。

另请注意:您放入 services.ts 中的内部模块是一个错误的模式,关键字已弃用。请参阅上面链接的手册。

以下是我最终成功实现它的方法:

修改services.ts(现在导出服务不使用模块关键字:

export class TechnologiesService {
  technologies: Array<string>;
  constructor() {
    this.technologies = ['Angular 2 Developer Preview', 'Express', 'Jade', 'Gulp', 'Material Design Lite', 'Polymer', 'Sass', 'Karma', 'Mocha', 'Should', 'npm', 'Bower'];
  }
}

假设一个 public 资源文件夹用于具有此层次结构的已编译 js 文件:

|--angular
     |----app.js
     |----services.js

导入顺序应该是:

/// <reference path="typings/angular2/angular2.d.ts" />
/// <reference path="services.ts" />
import {Component, View, bootstrap, NgFor} from 'angular2/angular2';
import {TechnologiesService} from 'angular/services'