Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了angularjs – 如何使用打字稿制作Angular服务?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用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
我希望它能让我的控制器中的这些货币充满来自服务器的数据.

解决方法

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

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

控制器应如下所示:

@H_492_7@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 – 如何使用打字稿制作Angular服务?全部内容,希望文章能够帮你解决angularjs – 如何使用打字稿制作Angular服务?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。