Services - Dependency Injection

Érdemes Service-be szervezni a logikákat. Ebben az esetben meg tudunk szabadulni az emitter-ekrtől.

tasks.service.ts

import {NewTaskData} from './task/new-task.module';
import {Injectable} from '@angular/core';

@Injectable({providedIn: "root"})
class TasksService {
  private tasks = [
    {
      id: 't1',
      userId: 'u1',
      title: "Vmi1",
      summary: "vmi summary 1",
      dueDate: '2025-12-31'
    },
    {
      id: 't2',
      userId: 'u1',
      title: "Vmi2",
      summary: "vmi summary 2",
      dueDate: '2025-12-31'
    },{
      id: 't3',
      userId: 'u1',
      title: "Vmi3",
      summary: "vmi summary 3",
      dueDate: '2025-12-31'
    },{
      id: 't4',
      userId: 'u1',
      title: "Vmi4",
      summary: "vmi summary 4",
      dueDate: '2025-12-31'
    }
  ];

  getUserTasks(userId: string) {
    return this.tasks.filter((task => task.userId === userId));
  }

  addTask(taskData: NewTaskData, userId: string) {
    this.tasks.unshift({
      id: new Date().getTime().toString(),
      userId:userId,
      title: taskData.title,
      summary: taskData.summary,
      dueDate: taskData.date
    })
  }

  removeTask(id: string) {
    this.tasks = this.tasks.filter( (t) => t.id !== id); //Újraépíti a tömböt, a kapott id nélkül!!
  }
}

new kulcsszot nem használjuk, angularra bízzuk a létrehozás, lehet konstruktorból vagy inject-el:

inject:

 private tasksService = inject(TasksService);

tasks.component:

import {Component, Input} from '@angular/core';
import {TaskComponent} from './task/task.component';
import {NewTaskComponent} from './new-task/new-task.component';
import {NewTaskData} from './task/new-task.module';
import {TasksService} from './tasks.service';

@Component({
  selector: 'app-tasks',
  standalone: true,
  imports: [
    TaskComponent,
    NewTaskComponent
  ],
  templateUrl: './tasks.component.html',
  styleUrl: './tasks.component.css'
})
export class TasksComponent {
  @Input({ required: true}) userId!: string;
  @Input({ required: true }) name!: string;
  isAddingTask = false;
  // private tasksService = new TasksService(); //nem jo megközelítés, DI kell helyette, ez így új példáanyt fog csinálni!!! A konstruktorba rakva singleton lesz

  // private taskService: TasksService;
  // // Dependeny Injections, a service-nek Injectable-nek kell lennie
  // constructor(taskService: TasksService) {
  //   this.taskService = taskService;
  // }

  // Dependeny Injections rövidebben:
  constructor(private tasksService: TasksService) {

  }

  get selectedUserTasks() {
    return this.tasksService.getUserTasks(this.userId);
  }

  onCompleteTask(id: string) {}

  onStartAddTask() {
    this.isAddingTask = true;
  }

  onCancelAddTask() {
    this.isAddingTask = false; //el fogja távolítani az if miatt a <app-new-task> komponent!!!!
  }

  onAddTask(taskData: NewTaskData) {

    this.isAddingTask = false;
  }
}