I just started off with Angular2 quick start project. Have a simple application working. I added DataService
class, so that the code will have separation of concern.
Initially I've added the DataService
class write after the my main component of app which is MyAppComponent
like below.
import {Component, View} from 'angular2/core';
import {NgFor} from 'angular2/common';
import {bootstrap} from 'angular2/platform/browser';
@Component({
'selector': 'my-app',
template: `<div *ngFor="#item of items">{{item}}</div>`,
directives: [NgFor],
providers: [DataService] //taking service as injectable
})
export class MyAppComponent {
items: Array<number>;
constructor(service: DataService) {
this.items = service.getItems(); //retrieving list to bind on the UI.
}
}
//created service, but its after the component which has meta annotation
export class DataService {
items: Array<number>;
constructor() {
this.items = [1, 2, 3, 4];
}
getItems() {
return this.items; //return the items list
}
}
bootstrap(MyAppComponent)
Above code compiles correctly, but at run-time it throws below error.
EXCEPTION: Cannot resolve all parameters for MyAppComponent(undefined). Make sure they all have valid type or annotations.
After 2 hours playing with the code, I shifted the DataService
just above the MyAppComponent
which got worked. I'm really glad that issue solved.
But I'm very curious to know that, why it wasn't working if I placed DataService
class right after the class
with MetaAnnotation
over it?
Edit
I tried solution give by @Günter Zöchbauer like below,
import {Component, View, Inject, forwardRef} from 'angular2/core';
import {NgFor} from 'angular2/common';
import {bootstrap} from 'angular2/platform/browser';
@Component({
'selector': 'my-app',
template: `<div *ngFor="#item of items">{{item}}</div>`,
directives: [NgFor],
providers: [DataService] //tried commenting this still throws error.
})
export class MyAppComponent {
items: Array<number>;
constructor(@Inject(forwardRef(() => DataService)) service: DataService) {
this.items = service.getItems();
}
}
but still getting error in console. which looks wiered
EXCEPTION: TypeError: Cannot read property 'toString' of undefined