javascriptangulartypescripttypescript1.5

Angular2 - Reference error when splitting application in different files


I am trying to modularize an Angular 2 application, having the services in a different file:

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

These files compile to js without error, but when running the app in the browser I get:

Uncaught ReferenceError: Service is not defined

Any idea on how to solve this?


Solution

  • Here is how I finally managed to make it work:

    Modified services.ts (now exporting the service and not using the module keyword:

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

    Assuming a public resources folder for compiled js files with this hierarchy:

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

    The import sequence should be:

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