[Ionic] Data Model and Observables

The content of this page are summarized from Mark Newman’s lecture notes.

Data Model

A data model is something that:

  • Does not have a UI
  • Represents an Entity within the system, including data and operations

For example, for Tour of Heroes:

  • Hero:
    • Name
    • Powers
    • functions to retrieve and modify these
  • HeroManager
    • The list of Heroes
    • functions to retrieve and modify these

Manager Pattern is a class that curates (creates, provides access, deletes) a collection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
export class Hero {
private heroName: string;
private heroId: number;
private heroPowers: string[];

public constructor(private heroName: string,
private heroId: number,
private heroPowers: string[] = []) {

}

public setName(newName: string): void {
this.heroName = newName;
}

public getName(): string {
return this.heroName;
}

public getId(): number {
return this.heroId;
}

public getPowers(): string[] {
return this.heroPowers;
}

public setPowers(newPowers: string[]): void {
this.heroPowers = newPowers;
}

public addPower(newPower: string): void {
this.heroPowers.push(newPower);
}

public removePower(powerToRemove: string) : void {
if (this.heroPowers.indexOf(powerToRemove) != -1) {
this.heroPowers.splice(this.heroPowers.indexOf(powerToRemove), 1);
}
}

public toString() : string {
return this.heroName + "(" + this.heroId + ") " + this.heroPowers;
}
}
  • HeroManager Model
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

import { Hero } from './hero';

var nextHeroId: number = 100;

export class HeroManager {

private heroes: Object = {};

public constructor() {

}

public createHero(heroName: string, heroPowers: string[] = []) {
let heroId = this.getNextHeroId();
let hero = new Hero(heroName, heroId, heroPowers);
this.heroes[heroId] = hero;
}

private getNextHeroId(): number {
return nextHeroId++;
}

public getHeroById(id: number): Hero {
return this.heroes[id];
}

public getHeroByName(name: string): Hero {
let heroList = this.getHeroes();
for (let i in heroList) {
if (heroList[i].getName() === name) {
return heroList[i];
}
}
return undefined;
}

public getHeroes(): Hero[] {
let heroesList: Hero[] = [];
for (let key in this.heroes) {
heroesList.push(this.heroes[key]);
}
return heroesList;
}

public removeHero(hero: Hero) {
delete this.heroes[hero.getId()];
}

public removeHeroById(id: number) {
delete this.heroes[id];
}
}