ngHeroes
  • πŸ‘€About
  • #0: πŸ’ƒ Introduction
  • #1: βŒ› Installations
  • #2: πŸ…° Angular kicks in
  • #3: πŸ“ Component
  • #4: ✏ A new component
  • #5: πŸ’Ό Class
  • #6: πŸ“₯ Property binding
  • #7: πŸ“€Event binding
  • #8: πŸ“Ž Element ref - #
  • #9: πŸ“‹ The To Do list
  • #10: βž• New component: todo-item
  • #11: β›“ Interface
  • #12: πŸ“ŒAdd items
  • #13: 🚧 Refactor App Component
  • #14: πŸ’… Adding Style
  • #15: πŸ”‹ Creating a Service
  • #16: 🎁 Add Items Using the Service
  • #17: πŸ’ΎLocal storage
  • #18: πŸ—‘ Remove item
  • #19: πŸ”˜ Adding a checkbox
  • #20: πŸ›° Deploy to GitHub Pages
  • #21: πŸ’ͺ Enrich the todo-item component
  • Appendix 1: Generating a new project
  • Appendix 2: Tutorial Extensions
Powered by GitBook
On this page

Was this helpful?

#16: 🎁 Add Items Using the Service

Let's improve our service by adding more abilities that will be used by our components. First - we'll implement adding an item to the list.

Adding an item

We'll add a new method to the service, called addItem, like so:

src/app/services/todo-list.service.ts
addItem(item: TodoItem) { 
  this.todoList.push(item);
}

Now we can change our list-manager component to call the addItem method directly from the service:

src/app/list-manager/list-manager.component.ts
addItem(title: string) {
    this.todoListService.addItem({ title });
}
  • Note that the service's method expects the whole item, while the component's method expects only the title and constructs the item. (You may decide to let the service construct the item from the title.)

  • There may be additional logic when calling these methods, i.e. saving the changes in a database (which we'll implement later).

  • A better way to handle data is using immutable objects, but that's a bigger topic than we can cover in this tutorial at the moment.

Previous#15: πŸ”‹ Creating a ServiceNext#17: πŸ’ΎLocal storage

Last updated 6 years ago

Was this helpful?