angularjs – 如何使用打字稿制作Angular服务?
发布时间:2020-12-17 07:08:57 所属栏目:安全 来源:网络整理
导读:我有一个使用typescript和AngularJS的服务代码,如下所示: /// reference path='../_all.ts' /module bankApp { 'use strict'; export class MDCurrencyService implements IMDCurrencyService { httpService: ng.IHttpService; promise: ng.IPromisevoid; c
我有一个使用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); 控制器应如下所示: 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); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- angular6学习(五):创建组键
- 在_servicename_中的下划线是什么意思在AngularJS测试?
- 单元测试 – 如何测试AngularJS自定义提供程序
- webservice soap WSDL中的tns字段什么意思?
- twitter-bootstrap – bootstrap词缀 – 底部不起作用
- 一个Docker附加参数引起的网络服务异常
- Advanced Programming in UNIX Environment Episode 12
- 如何在vagrant ssh bash中配置颜色
- 在angular5中使用sw预缓存时排除子网站网址
- 如何在Scala Play中使用变量键解析JSON?