Difference between service and model in Angular 2?

I open Angular2 and I found a quick launch project on the Internet to understand the structure. I have three folders inside another: components, services and models. I understand what a component is, and since I understand that a service is a singleton, where I want to save my data.

The fact is that I have this file inside the 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 folder inside the models:

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 a ServiceService. Is it because I can have multiple instances of tasks? If so, can I have multiple instances of TaskService and not a singleton? If not, how can the compiler know when it is a service and when it is a model? Due to the suffix?

Thank.

+4
3

@Injectable -

, !

, , , , , , Angular, .

, Task - Injectable.

+6

. , . https://angular.io/docs/ts/latest/tutorial/toh-pt4.html

HeroService? ! HeroService :

heroService = HeroService();// ,

, HeroService. - HeroService, , , . .

, . , ? .

AppComponent HeroService. . ? ? .

, ... , ... , !

. . , .

+2

: ( ). , .

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

: . (/ , ,...). @Injectable(). , , , , , .

angular 2: https://angular.io/docs/ts/latest/guide/architecture.html

+2

Source: https://habr.com/ru/post/1667700/


All Articles