How do I make an Angular service using typescript?

I have a utility code using typescript and AngularJS like this:

/// <reference path='../_all.ts' />

module bankApp {
    'use strict';

    export class MDCurrencyService implements IMDCurrencyService {
        httpService: ng.IHttpService;
        promise: ng.IPromise<void>;

        constructor($http: ng.IHttpService,
            $q : ng.IQService) {

            this.httpService = $http;
        }

        get(): MDCurrency[] {
            var promise = this.httpService.get('/Master/CurrencyGetAll').then(function (res) {
                return res.data;
            });
            return promise;
        }


        save(cur: MDCurrency) {
            this.httpService.post('/Master/CurrencySave', cur);

        }

        softDelete(id: string)
        { }

        hardDelete(id: string)
        { }




    }
}

      

I will use my controller like this:

this.currencies = $scope.currencies = mdCurrencyService.get();

      

How can I create an angular $ http service using typescript? I would like this currency in my controller to be populated with data from the server.

+3


source to share


1 answer


The service should look like this. Don't forget to register the service in the module:

export class MDCurrencyService implements IMDCurrencyService {
    constructor(private $http: ng.IHttpService, private $q : ng.IQService) {
    }

    get(): ng.IPromise<MDCurrency[]> {
        var deferred = this.$q.defer();
        this.$httpService.get('/Master/CurrencyGetAll').then(response => {
            deferred.resolve(response.data);
        }).catch( reason => {
            deferred.reject(reason);
        });
        return deferred.promise;
    }
}

angular.module("TheModule").service("mdCurrencyService", MDCurrencyService);

      

The controller should look like this:

mdCurrencyService.get().then(currencies => {
   this.$scope = currencies;
}).catch( reason => {
   alert("something went wrong!");
});

      



EDIT:

The code can be simplified, the $ q service is not required:

export class MDCurrencyService implements IMDCurrencyService {
    constructor(private $http: ng.IHttpService) {
    }

    get(): ng.IPromise<MDCurrency[]> {          
        return this.$httpService.get('/Master/CurrencyGetAll')
                   .then(response => response.data);
    }
}

angular.module("TheModule").service("mdCurrencyService", MDCurrencyService);

      

+7


source







All Articles