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.
/// <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?
The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism.
We use the @Inject parameter decorator to instruct Angular we want to resolve a token and inject a dependency into a constructor. We use the @Injectable class decorators to automatically resolve and inject all the parameters of class constructor.
26) Which of the following components can be injected as a dependency in AngularJS? Answer: D is the correct answer. The "Application Module" can be injected as a dependency in AngularJS.
An injection (often and usually referred to as a "shot" in US English, a "jab" in UK English, or a "jag" in Scottish English and Scots) is the act of administering a liquid, especially a drug, into a person's body using a needle (usually a hypodermic needle) and a syringe.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With