【问题标题】:How do I make an Angular service using typescript?如何使用打字稿制作 Angular 服务?
【发布时间】:2015-08-21 11:26:43
【问题描述】:

我有一个使用 typescript 和 AngularJS 的服务代码,如下所示:

/// <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)
        { }




    }
}

我会这样使用我的控制器:

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

如何使用打字稿制作角度服务 $http? 我希望我的控制器中的 this.currencies 将填充来自服务器的数据。

【问题讨论】:

    标签: angularjs typescript


    【解决方案1】:

    服务应如下所示。不要忘记在模块中注册服务:

    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);
    

    控制器应如下所示:

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

    编辑:

    代码可以简化,不需要$q服务:

    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);
    

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 2016-10-27
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2015-03-21
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多