注射剂在 angular 2.0 中不起作用

Injectables not working in angular 2.0

我最近开始玩 Angular2。我已经尝试让注射剂发挥作用大约半天了,但我仍然无法弄清楚我做错了什么。

为了尽可能简单,我复制了官网5 Min Quickstart的代码。演示本身工作正常,但是当我尝试使用注射剂时,我收到一条错误消息

ORIGINAL ERROR: Cannot resolve all parameters for MyAppComponent. Make sure they all have valid type or annotations.

我的打字稿文件

/// <reference path="typings/angular2/angular2.d.ts" />
import {Component, View, bootstrap,} from 'angular2/angular2';

class Names {}

// Annotation section
@Component({
    selector: 'my-app',
    injectables: [Names]
})
@View({
    template: '<h1>Hello {{ name }}</h1>'
})
// Component controller
class MyAppComponent {
    name: string;
    constructor(names: Names) {
        this.name = 'Alice';
    }
}

bootstrap(MyAppComponent);

P.S。与 5 Min Quickstart 一样,我使用 TraceurSystemJSAngular2 alpha (23)

有人知道我错过了什么吗?

您的编译器不会将参数属性添加到 MyAppComponent(通过查看您的 pluker)。我认为这是问题所在。如果你加上

MyAppComponent.parameters = [[Names]]

那么一切都会好起来的。

  1. Here 是你的修复工具。
  2. Here 与 TS 中的相同示例(使用 ES6)

UPD 感谢@GrayFox 指出正确的方法(见下面的评论):

For future references - use --emitDecoratorMetadata flag when using tsc or add emitDecoratorMetadata: true to the configuration if you're using gulp-typescript

查看 TypeScript 编译器选项 here(您可以在那里找到 emitDecoratorMetada)。

放这个:

 <PropertyGroup Condition=" '$(Configuration)' == 'Debug' " >
   <DebugSymbols>true < /DebugSymbols>
   < TypeScriptRemoveComments > false < /TypeScriptRemoveComments>
   < TypeScriptSourceMap > true < /TypeScriptSourceMap>
   < TypeScriptAdditionalFlags > $(TypeScriptAdditionalFlags)--emitDecoratorMetadata < /TypeScriptAdditionalFlags>
 < /PropertyGroup>
 < PropertyGroup Condition= " '$(Configuration)' == 'Release' " >
   <DebugSymbols>true < /DebugSymbols>
   < TypeScriptRemoveComments > true < /TypeScriptRemoveComments>
   < TypeScriptSourceMap > false < /TypeScriptSourceMap>
   < TypeScriptAdditionalFlags > $(TypeScriptAdditionalFlags)--emitDecoratorMetadata < /TypeScriptAdditionalFlags>
 < /PropertyGroup>

最后进入你的 *.njsproj 文件。