gpt4 book ai didi

javascript - Aurelia 中的 Typescript 自动注入(inject)

转载 作者:数据小太阳 更新时间:2023-10-29 04:43:48 34 4
gpt4 key购买 nike

我是 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 文件添加到我的项目中并在编译器选项中设置该标志,但随后出现了一堆错误(重复标识符)。我该如何修复这些错误。我需要在"file"中添加一些东西吗?究竟是什么?

这是我的 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.

像下面这样尝试,您需要在 Type Script 的 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": [
// ...
]
}

文章片段截图:

enter image description here

关于 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 代码片段: 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));
});

关于javascript - Aurelia 中的 Typescript 自动注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34540009/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com