4
votes

I'm using Angular 1.4, TypeScript 1.6, and CommonJS external modules.

I have three files in this module:

paginator.module.ts
paginator.service.ts
paginator.controller.ts

paginator.module.ts looks like this:

import PaginatorService = require('./paginator.service');
import PaginatorCtrl = require('./paginator.controller');

var Paginator = angular.module('paginator', [])
  .service('pageService', PaginatorService)
  .controller('pageCtrl', PaginatorCtrl);

Here's paginator.service.ts:

class PaginatorService {
    currentPage: number;
    pageCount: number;
    pages: Array<Array<any>>;

    constructor() {
      this.currentPage = 0;
    }
  }

export = PaginatorService;

In paginator.controller.ts, I inject pageService along with $scope using dependency injection, and I expect to see type information when I give it a type of PaginatorService.

class PaginatorController {
  scope: ng.IScope;
  pageService: PaginatorService;

  /**
   * @param  $scope
   * @param  pageService
   */
  constructor($scope: ng.IScope, pageService: PaginatorService) {
    this.scope = $scope;
    this.pageService = pageService;
  }
 export = PaginatorController;

However, I receive the following error in atom-typescript:

TS Error: Cannot find name 'PaginatorService'.

What I've tried

  • Adding another import statement in paginator.controller.js file resolves the issue (i.e. import PaginatorService = require('./paginator.service');). However, this seems redundant as I've already require()d this service when setting up my Angular module.

  • I tried using tsc --declaration on paginator.service.js to generate a declaration file, which you can view below, but it didn't resolve the issue.

Autogenerated d.ts file

declare class PaginatorService {
    currentPage: number;
    pageCount: number;
    pages: Array<Array<any>>;
    constructor();
}
export = PaginatorService;
  • Modifying this declaration file to declare a module (ambient declaration?) seemed to work, but manually doing this for the 100+ Angular services I need to migrate to CommonJS syntax makes this approach problematic.

My question is this: What is a recommended pattern for using CommonJS + Angular + TypeScript to require the correct modules and then let Angular's dependency injection take over from there, especially across files?

Thanks!

1

1 Answers

1
votes

TS Error: Cannot find name 'PaginatorService'.

You are doing

export class PaginatorService 

You need to import it as

ES6

import {PaginatorService} from "./paginatorService"; 

or

Old style

import paginatorService = require("./paginatorService"); 
import PaginatorService = paginatorService.PaginatorService;