angularjs - 如何使用 typescript 制作 Angular 服务?

标签 angularjs typescript

我有一个使用 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)
        { }




    }
}

我将像这样使用我的 Controller :

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

如何使用 typescript 制作 angular.service $http? 我希望这样我的 Controller 中的 this.currencies 将填充来自服务器的数据。

最佳答案

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

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

Controller 应该是这样的:

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

关于angularjs - 如何使用 typescript 制作 Angular 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30684705/

相关文章:

javascript - 当 Angular JS 代码过于模糊时如何阅读

angularjs - Angular 翻译 - 格式化日期

javascript - Angular 脚本加载 : how to include all scripts in just one call

forms - Angular 4 根据服务器的响应提交显示错误

angular - NGRX 中效果执行的顺序

html - 处理音频标签上的 404 错误

javascript - 使用 angularjs 单击上一个和下一个按钮更改项目列表的事件状态

javascript - 如何将 Rails 变量传递给 AngularJS 配置

sockets - 删除带有套接字的消息

intellij-idea - 如何设置 WebStorm/IntelliJ,以便 Grunt 控制台的输出链接到文件,就像调用 tsc 的 FileWatcher 一样