Skip to content

Instantly share code, notes, and snippets.

@tstpierre
Created March 29, 2016 17:00
Show Gist options
  • Save tstpierre/864bea8c2a49b77fd40dcd6fc6fa2770 to your computer and use it in GitHub Desktop.
Save tstpierre/864bea8c2a49b77fd40dcd6fc6fa2770 to your computer and use it in GitHub Desktop.
Some Angular 1 strong typing from http service to controller usage
module app.services {
export interface IUserModel {
id: number;
firstName: string;
lastName: string;
}
export interface IFindUserByIdRequestModel {
id: number;
}
export interface IUserService {
findUserById (model: IFindUserByIdRequestModel): ng.IPromise<IUserModel>;
}
}
module app {
export interface IUserControllerViewModel {
user: app.services.IUserModel;
getFullname(): string;
}
class UserController implements IUserControllerViewModel {
user: app.services.IUserModel;
static $inject = ['UserService'];
constructor (private UserService: app.services.IUserService) {
}
// public by default in TS
getFullname = (): string => {
return this.user.firstName + ' ' + this.user.lastName;
}
// example of internal logic not exposed from viewmodel interface
private getUser = (): void => {
var that = this;
this.UserService
.findUserById({
id: 1
})
.then(successHandler, errorHandler);
function successHandler (user: app.services.IUserModel) {
that.user = user;
}
function errorHandler (error: ng.IHttpPromiseCallbackArg<any>) {
that.user = undefined;
}
}
}
angular
.module('app')
.controller('UserCtrl', UserController);
}
module app.services {
class UserService implements IUserService {
// angular dependency injection for minify/uglify-safe
static $inject = ['$q', '$http'];
constructor (private $q: ng.IQService,
private $http: ng.IHttpService) { }
findUserById = (model: IFindUserByIdRequestModel): ng.IPromise<IUserModel> => {
var url: string = 'path-to-api/users/' + model.id;
var deferred: ng.IDeferred<IUserModel> = this.$q.defer();
this.$http
.get('path-to-api/users/')
.then(successHandler, errorHandler);
return deferred.promise;
function successHandler (success: ng.IHttpPromiseCallbackArg<IUserModel>) {
deferred.resolve(success.data);
}
function errorHandler (error: ng.IHttpPromiseCallbackArg<any>) {
deferred.reject(error);
}
}
}
angular
.module('app')
.service('UserService', UserService);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment