繁体   English   中英

Typescript和AngularJS 1.5:如何处理导出类

[英]Typescript and AngularJS 1.5: How to handle export class

我有这个module.ts文件:

import { IHttpService, IPromise } from 'angular';

export class ProductService {
    static $inject = ["$http"];
    constructor(private $http: IHttpService) { }

    loaded: boolean = false;
    promise: IPromise<{ data: any }>;

    getProducts(): IPromise<{ data: any }> {
        if (!this.loaded) {
            this.loaded = true;
            this.promise = this.$http.get('/products.json');
        }
        return this.promise;
    }
}

var module = angular.module("psShopping", ["ngComponentRouter"]);
module.value("$routerRootComponent", "shoppingApp");
module.service('products', ProductService);

并将其转译/编译为module.js:

"use strict";
var ProductService = (function () {
    function ProductService($http) {
        this.$http = $http;
        this.loaded = false;
    }
    ProductService.prototype.getProducts = function () {
        if (!this.loaded) {
            this.loaded = true;
            this.promise = this.$http.get('/products.json');
        }
        return this.promise;
    };
    ProductService.$inject = ["$http"];
    return ProductService;
}());
exports.ProductService = ProductService;
var module = angular.module("psShopping", ["ngComponentRouter"]);
module.value("$routerRootComponent", "shoppingApp");
module.service('products', ProductService);

有问题的行是: exports.ProductService = ProductService; 如果我手动删除它-该应用程序运行完美。 但是,如果我这样离开,在浏览器控制台中,我会收到一个错误“未定义导出”。 关于这个还能做什么? 我不能仅从.ts文件中删除“导出”,因为此类已在其他文件中使用(我将其导入到那里)。 我尝试了不同的编译器选项,但它给了我不同的错误(例如“未定义定义”等),我不确定如何处理。 也许有一种方式,TSC不会产生这一行?

每当您在打字稿中使用importexport关键字时,便会将文件转换为模块。

模块被设计为可与诸如commonjsamdes6systemjs等模块系统一起使用...

如果您尝试在不使用模块加载器或捆绑程序(例如systemjs,webpack,browserify,jspm等)的情况下在浏览器中加载原始脚本,则无法使用外部模块(因此无法使用导入/导出) )。

您仍然可以使用绝对类型的类型,但是必须通过///<reference />标记加载它们。

如果使用打字稿2.0,则在运行时默认也可以输入诸如angular的类型并导入

npm install @types/angular

通常,这些类型将公开全局名称空间声明,您现在可以在整个应用程序中使用它。

例如,在您的情况下,angular公开了ng命名空间,您可以像这样使用它:

  promise: ng.IPromise<{ data: any }>;

您还可以轻松地为其别名:

import IPromise = ng.IPromise

请注意,此导入的行为与模块导入不同(只是别名)。

如果您打算做一些琐碎的应用程序之外的工作,我强烈建议您使用模块加载程序(例如webpack)来为浏览器编译和捆绑该应用程序。 仅使用普通脚本有很多限制。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM