1

Recently ive made an angular 2 todo app that is working, however im not using a service for this app, and ive heard that using a service is the way to go. But i am not entirely sure how i refactor my code so that i can push data into my service instead.

My component:

import { Component } from '@angular/core';
import { Todo } from './todo';
import { TODOS } from './mock-todos';
import { TodoService } from './todo.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass'],
  providers: [TodoService]
})
export class AppComponent {
  title = 'Todo List';
  selectedTodo: Todo;
  completed = false;

  constructor(private todoService: TodoService){

  }

  onSelect(todo: Todo): void {
    this.selectedTodo = todo;
  }

  addTodo(value: any) {
     this.todoService.addTodo(value);
     console.log(value);
  } 
  deleteTodo(todo) {
    this.todos.splice(todo,1);
    console.log("This todo has been deleted"+ todo);
  }
  completedTodo(todo){
    todo.isCompleted = !todo.isCompleted;
    todo.completed = !todo.completed;
  }


}

My Service:

import { Injectable } from '@angular/core';
import { Todo } from './todo';

@Injectable()
export class TodoService {
  todos: Todo[] = [];
  lastId: number = 0;

  constructor() { }

  addTodo(value: any) {
    this.todos.push(value);
    console.log("This was pushed");
  } 

}

I thought i was able to use the service to push my data there , instead of having the component to handle this. So the service can be used for other components.

I would be happy to get a reply to this.

1 Answer 1

2

Instead of performing actions on variable in component, you can instead store your todos in the service, and when you want to make changes to your array, you just call the service functions. This is pretty well covered in the Services tutorial in the official docs, but just to throw in a short example for getting and adding todos:

In component, get the todos in OnInit and store in local variable.

ngOnInit() {
  this.todos = this.todoService.getTodos()
} 

The adding of a todo, call the service to do the adding.

addTodo(todo) {
  this.todoService.addTodo(todo)
}

Your TodoService looks codewise totally right, so you were almost all there with your code :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.