-
-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathdata.service.ts
54 lines (42 loc) · 1.29 KB
/
data.service.ts
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
54
import { Injectable } from '@angular/core';
import { BehaviorSubject } from "rxjs/BehaviorSubject";
export class DataItem {
constructor(public id: number, public name: string) { }
}
@Injectable()
export class DataService {
private _intervalId;
private _counter = 0;
private _currentItems: Array<DataItem>;
public items$: BehaviorSubject<Array<DataItem>>;
constructor() {
this._currentItems = [];
for (var i = 0; i < 3; i++) {
this.appendItem()
}
this.items$ = new BehaviorSubject(this._currentItems);
}
public startAsyncUpdates() {
if (this._intervalId) {
throw new Error("Updates are already started");
}
this._intervalId = setInterval(() => {
this.appendItem();
this.publishUpdates();
}, 200);
}
public stopAsyncUpdates() {
if (!this._intervalId) {
throw new Error("Updates are not started");
}
clearInterval(this._intervalId);
this._intervalId = undefined;
}
private publishUpdates() {
this.items$.next([...this._currentItems]);
}
private appendItem() {
this._currentItems.push(new DataItem(this._counter, "data item " + this._counter));
this._counter++;
}
}