Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between service and model in Angular 2?

I'm discovering Angular2 and I found a quick start project on internet to understand the structure. I have three folders inside of another: components, services and models. I understand what is a component and as I understand a service is a singleton where I want to persist my data.

The thing is that I have this file inside services folder:

import {Injectable} from "@angular/core";
import {Task} from "../models/task";

@Injectable()
export class TaskService {

    private tasks:Array<Task> = [
        new Task("Task 1", false),
        new Task("Task 2", false),
        new Task("Task 3", false),
    ];

    getTasks():Array<Task> {
        return this.tasks;
    }

    addTask(name:string) {
        this.tasks.push(new Task(name, false));
    }

}

And I have this one inside models folder:

export class Task {

    constructor(public name:string, public done:boolean) {
    }

    toggleDone() {
        this.done = !this.done;
    }
}

But I'm not sure why Task is considered a model and TaskService a service. Is it because I can have multiple instances of Tasks? If so, then can I have multiple instances of TaskService and is not a singleton? If not, how can the compiler know when it is a service and when it is a model? Because of the suffix?

Thank you.

like image 322
Kimy BF Avatar asked Dec 15 '22 01:12

Kimy BF


1 Answers

@Injectable is the answer

We register an injectable class, and we won't have to instantiate it!

We register it as a provider in the app modules, register it as a provider in our component, and hey presto you're gonna get that injected, straight magic, thanks Angular, you dat boi.

And what's more, now our component won't even have to know anything about the Task class - it's already included in our Injectable service.

like image 174
Simon Visser Avatar answered Dec 28 '22 10:12

Simon Visser