user944513 user944513 - 2 months ago 123
AngularJS Question

how to add service in angular 2 getting error while injecting?

I added one service in my demo project .

import {Injectable} from "@angular/core";
@Injectable()
export class TodoService {
todos = [];
}


and injecting this in my component .

import {Component} from "@angular/core";
import {TodoService} from "./todo-service";

@Component({
selector :'todo-input',
template: '<div><button (click)="btnClick(in)">Add item</button><input type="text" #in/></div>'
})

export class Todo {
constructor(public todoservice: TodoService) {

}

btnClick(val) {
this.todoservice.todos.push(val.value);
console.log(this.todoservice.todos);
}
}


I am getting this error

or: Error: Can't resolve all parameters for Todo: (?).
at CompileMetadataResolver.getDependenciesMetadata (https://unpkg.com/@angular/compiler/bundles/compiler.umd.js:14388:21)
at CompileMetadataResolver.get


here is my code
http://plnkr.co/edit/bYsvcXFsr1ZPX85JUVPk?p=preview

Answer

Change your app/todo-service.js file to app/todo-service.ts

And then add it to providers list of your component or module:

import {TodoService} from "./todo-service";

@Component({
    selector :'todo-input',
    providers: [TodoService], <== this line
    template: '..'
})

export class Todo {

Plunker