[Angular 2] Use Service use Typescript

时间:2024-01-11 21:56:32

When creating a service, need to inject the sercive into the bootstrap():

import {bootstrap, Component, View} from "angular2/angular2";
import {TodoInput} from "./todoInput";
import {TodoService} from "./todoService"; @Component({
selector:'app'
})
@View({
directives: [TodoInput],
template: `
<div><todo-input></todo-input></div>
`
})
class App{ } bootstrap(App, [TodoService]);

todoService.js

export class TodoService{
todos: string[] = []; addTodo(value: any):void {
this.todos.push(value);
}
}

inputTodo.js:

import {Component, View} from "angular2/angular2";
import {TodoService} from "./todoService"; @Component({
selector: 'todo-input'
}) // Define a ref by using xxx-YYY
// Reference a ref by using xxxYyy
@View({
template: `
<input type="text" #log-me />
<button (click)="onClick($event, logMe.value)">Log Input</button>
`
})
export class TodoInput{
constructor(
public todoService:TodoService //pulbic make todoService global available for the class
){
console.log(todoService);
} onClick(event , value){
this.todoService.addTodo(value);
console.log(this.todoService.todos);
}
}