Skip to content

Instantly share code, notes, and snippets.

@zhentian-wan
Created March 19, 2016 19:36
Show Gist options
  • Save zhentian-wan/503062da87f03b261eb2 to your computer and use it in GitHub Desktop.
Save zhentian-wan/503062da87f03b261eb2 to your computer and use it in GitHub Desktop.
Inject service TypeScript way
import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/bootstrap';
import {TodoService} from './TodoService';
import {TodoInput} from './TodoInput';
@Component({
selector: 'app',
directives: [TodoInput],
template: `
<todo-input></todo-input>
`
})
class App {
}
// []: we can inject service which can be used for the whole app
bootstrap(App, [
TodoService
]);
import {Component} from 'angular2/core';
import {TodoService} from './TodoService';
@Component({
selector: 'todo-input',
template: `
<div>
<input #myInput type="text">
<button (click)="onClick(myInput.value)">Click me</button>
</div>
`
})
export class TodoInput{
constructor(public todoService: TodoService){
}
onClick(todo: string){
this.todoService.todos.push(todo);
console.log(this.todoService.todos);
}
}
export class TodoService{
todos = [];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment