Created
March 19, 2016 19:36
-
-
Save zhentian-wan/503062da87f03b261eb2 to your computer and use it in GitHub Desktop.
Inject service TypeScript way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
]); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class TodoService{ | |
todos = []; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment