注入时如何在Angular 2中添加服务错误?

时间:2016-09-11 13:11:27

标签: angular angular2-routing

我在我的演示项目中添加了一项服务。

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

并将其注入我的组件中。

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);
    }
}

我收到此错误

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 

这是我的代码 http://plnkr.co/edit/bYsvcXFsr1ZPX85JUVPk?p=preview

1 个答案:

答案 0 :(得分:2)

将您的app/todo-service.js文件更改为app/todo-service. t s

然后将其添加到组件或模块的providers列表中:

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

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

export class Todo {

<强> Plunker