打字稿:无法在构造函数中使用 : 符号编译文件

Typescript: can't compile file with : notation in constructor

本文关键字:符号 编译 文件 构造函数      更新时间:2023-09-26

我正在关注Ionic(使用Angular 2)应用程序的一些示例。所有类的构造函数都有类似的东西:

export class UserService {
    constructor(http: Http) {
        this.http = http;
    }
}

但编译器输出此错误:

Unexpected token (14:17)
  12 |  }
  13 | 
> 14 |  constructor(http: Http)
at Parser.pp.raise (/home/cbenseler/dev/apps/expressoapp/node_modules/babylon/index.js:1425:13)

这可能是我的应用程序(使用 babel 和 webpack)的设置问题,但我找不到问题所在。

webpack.config.js 文件包含以下内容:

module: {
    loaders: [
      {
        test: /'.js$/,
        loader: 'babel',
        query: {
          presets: ['es2015'],
          plugins: ['transform-decorators-legacy']
        },
        include: path.resolve('app'),
        exclude: /node_modules/
      },
      {
        test: /'.js$/,
        include: path.resolve('node_modules/angular2'),
        loader: 'strip-sourcemap'
      }
    ],
    noParse: [
      /es6-shim/,
      /reflect-metadata/,
      /zone'.js('/|'')dist('/|'')zone-microtask/
    ]
  }

有人知道吗?

我会看到一件可能会错过的事情:

  • 您忘记导入 Http 类,因此编译器无法解析它:

    import {Http} from 'angular2/http';
    

编辑

如果仅使用 ES6(似乎是这种情况),则可以在参数级别使用类型。在这种情况下要注入,您需要使用这样的方法:

@Injectable()
export class UserService {
  constructor(http) {
    this.http = http;
  }
  static get parameters() {
    return [[Http]];
  }
}

有关更多详细信息,请参阅以下链接:

  • angular2 在使用 ngFormModel (ES6) 时无法读取未定义的属性"验证器"
  • https://medium.com/@euphocat/angular2-router-in-es6-7-and-dependency-injection-b96944c3ba2e#.qat3cl6b4