我有一个使用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? 我希望它能让我的控制器中的这些货币充满来自服务器的数据。
答案 0 :(得分:7)
该服务应如下所示。不要忘记在模块中注册服务:
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);