我有一个使用 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/