微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – Aurelia中的Typescript自动注入

我是Typescript和Aurelia的新手.
我试图让@autoinject装饰器在VS2015 ASP.NET MVC 6项目中工作.

这是我的代码

import {autoinject} from "aurelia-framework";
import {HttpClient} from "aurelia-http-client";

@autoinject()
export class App {
       http: HttpClient;
       constructor(httpClient: HttpClient) {
          this.http = httpClient;
       }

       activate() {
          this.http.get("/api/test/")...
       }
}

当我运行这个时,我得到一个错误,说this.http是未定义的.

我相信我需要添加TypeScript的emitDecoratorMetadata标志,但我不知道如何.

我已经尝试将tsconfig.json文件添加到我的项目并在编译器选项中设置该标志,但后来我得到一堆错误(重复标识符).
我该如何解决这些错误.我需要在“文件”中添加一些内容吗?到底是什么?

这是我的config.js文件

System.config({
  baseURL: "/",defaultJSExtensions: true,transpiler: "typescript",paths: {
    "npm:*": "jspm_packages/npm/*","github:*": "jspm_packages/github/*"
  },map: {
    "aurelia-bootstrapper": "npm:aurelia-bootstrapper@1.0.0-beta.1","aurelia-framework": "npm:aurelia-framework@1.0.0-beta.1.0.7","aurelia-http-client": "npm:aurelia-http-client@1.0.0-beta.1","typescript": "npm:typescript@1.7.5",....
  }
  });

解决方法

@autoInject()如何工作?

Before you need to aware of TypeScript’s emitDecoratorMetadata flag causes the TypeScript compiler to polyfill the Metadata Reflection API and add a special decorator deFinition to the transpiled TypeScript code.

Aurelia’s @autoInject() decorator consumes the type Metadata created by TypeScript’s decorator and applies it to the class in the same way that the @inject(…) decorator does.

尝试如下所示,您需要在类型脚本的compilerOptions中启用新选项.

TS配置:

{
    "version": "1.5.1","compilerOptions": {
        "target": "es5","module": "amd","declaration": false,"noImplicitAny": false,"removeComments": false,"noLib": true,"emitDecoratorMetadata": true
    },"filesGlob": [
        "./**/*.ts","!./node_modules/**/*.ts"
    ],"files": [
        // ...
    ]
}

文章的片段截图:

关于emitDecoratorMetadata的文章
http://blog.durandal.io/2015/05/06/getting-started-with-aurelia-and-typescript/
http://www.danyow.net/inversion-of-control-with-aurelia-part-2/

可用类型脚本选项:
https://github.com/Microsoft/TypeScript/wiki/Compiler-Options

You can do it with Gulp-Typescript as well with Gulp option

选项:https://github.com/ivogabe/gulp-typescript#options
GitHub问题主题https://github.com/ivogabe/gulp-typescript/issues/100

Gulp Code代码段:
gulp.task(‘build-ts’,[],function(){

return gulp.src(paths.typescript)
    .pipe(plumber())
    .pipe(changed(paths.output,{extension: '.js'}))
    .pipe(sourcemaps.init())
    .pipe(ts({
      declarationFiles: false,noExternalResolve: true,target: 'es5',module: 'commonjs',emitDecoratorMetadata: true,typescript: typescript
    }))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(paths.output));
});

原文地址:https://www.jb51.cc/js/157756.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐