我创建这样的服务:
export class MDCurrencyService implements IMDCurrencyService {
httpService: ng.IHttpService;
handlerUrl: string;
constructor($http: ng.IHttpService) {
this.httpService = $http;
this.handlerUrl = '/Master/';
}
get(): MDCurrency[]{
var result: MDCurrency[] = [];
var resp: ng.IPromise<any> = this.httpService.get(this.handlerUrl +'GetAllCurrency')
.then((response: any): ng.IPromise<any> => this.handlerResponded(response, null));
resp.then((data) => {
if (data.is_success) {
data.data.forEach(c => {
var converted: MDCurrency = <MDCurrency>c;
converted.selectedCountry = null;
converted.selectedStatus = null;
result.push(converted);
});
return result;
}
else return null;
});
return result;
}
handlerResponded(response: any, params: any): any {
response.data.requestParams = params;
return response.data;
}
}
在controller
:
$scope.currencies = this.currencies = mdCurrencyService.get();
if ($scope.currencies.length > 0) {
console.log('entered'); //never executed
$scope.currencies.forEach(currency => {
for (var ii = 0; ii < this.statuses.length; ii++)
if ($scope.statuses[ii].Id == currency.Status)
currency.selectedStatus = this.statuses[ii];
});
}
但是$scope.currencies
从服务中填充forEach
从未执行过。
当$scope.currencies
被来自服务的数据填充时如何执行该代码?
答案 0 :(得分:2)
mdCurrencyService.get()
应该作为返回promise的异步服务来实现。它可以这样使用:
mdCurrencyService.get().then(function (currencies) {
// process result here
$scope.currencies = currencies;
});