Injectables not working in angular 2.0

陌路散爱 提交于 2019-12-29 07:26:08

问题


I recently started playing with Angular2. I've been trying to get injectables to work for about half a day now, but I still can't figure out what I'm doing wrong.

To keep it as simple as possible, I copied code from 5 Min Quickstart in the official webpage. Demo itself works fine, but when i try to use injectables, I get an error saying

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

My typescript file

/// <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. As in the 5 Min Quickstart, I'm using Traceur, SystemJS and Angular2 alpha (23)

Does anyone know what I'm missing?


回答1:


Your compiler does not add parameters properties to the MyAppComponent (from looking at your pluker). I think this is the problem. If you add

MyAppComponent.parameters = [[Names]]

then all will works well.

  1. Here is your plunker with fix.
  2. Here is the same example in TS (with ES6)

UPD Thanks to @GrayFox for pointing out the correct way (see the comment bellow):

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

See TypeScript compiler options here (you can find emitDecoratorMetada there).




回答2:


Put this:

 <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>

into your *.njsproj file at the end.



来源:https://stackoverflow.com/questions/30239758/injectables-not-working-in-angular-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!