简体   繁体   中英

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

Change your app/todo-service.js file to app/todo-service. t s

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM