Skip to content

Instantly share code, notes, and snippets.

@adhamankar
Last active November 1, 2015 21:01
Show Gist options
  • Save adhamankar/fadede965a9a6de2ceae to your computer and use it in GitHub Desktop.
Save adhamankar/fadede965a9a6de2ceae to your computer and use it in GitHub Desktop.
TypeScript+ Angular DataService based on observer pattern
module CommonServices {
export class DataService<T> {
public data: T;
private observerCallbacks = []; // Observer pattern implementation
public registerCallback = (callback) => {
this.observerCallbacks.push(callback);
};
public setData = (instance: T) => {
this.data = instance;
angular.forEach(this.observerCallbacks,(callback?: Function) => callback());
};
public getData = (): T => {
return this.data;
}
}
}
module Projects {
"use strict";
export class IterationDataService extends CommonServices.DataService<Iteration> {
public static Factory() {
return new IterationDataService();
}
}
}
//registration as data service
angular.module("projects", [])
.factory("IterationDataService", Projects.IterationDataService.Factory)
module Projects {
"use strict";
export class IterationDetailsCtrl {
public static $inject = ["$scope", "$http", "$state", "IterationDataService"];
constructor(public $scope: ng.IScope
, public $http: ng.IHttpService
, public $state: ng.ui.IStateService
, public IterationDataService: IterationDataService
) {
super($scope);
var me = this;
//setting data
$http.get(me.getUrl())
.success((data: Iteration) => {
me.iteration = data;
me.IterationDataService.setData(me.iteration);
});
//getting data
this.IterationDataService.registerCallback(() => {
me.iteration = this.IterationDataService.getData();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment