问题
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.
- Here is your plunker with fix.
- 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 addemitDecoratorMetadata: 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