我没有从 Angular 服务中恢复大量客户。
服务:
surchargeIndex.service('customerService', [
"$http", function ($http) {
this.get = function (customerType) {
if (customerType == "1") {
getProduction().then(function (result) { return result.data; });
} else if (customerType == "2") {
getTest().then(function (result) { return result.data; });
} else {
getAll().then(function (result) { return result.data; });
}
}
var getTest = function () {
return $http({
method: "GET",
url: "api/Customer/GetTest",
})
.success(function (data) {
return data;
});
};
var getProduction = function () {
return $http({
method: "GET",
url: "api/Customer/GetProduction",
})
.success(function (data) {
return data;
});
};
var getAll = function () {
return $http({
method: "GET",
url: "api/Customer/GetAll",
})
.success(function (data) {
return data;
});
};
Controller 调用:
$scope.getCustomers = function(customerType) {
$scope.showContent = false;
$scope.customers = customerService.get(customerType);
};
HTML:
<div ng-controller="CustomerController" data-ng-init="init()" class="col-md-2">
<select ng-model="customerKey" ng-options="customer.Key as customer.Value for customer in customers"></select>
</div>
每次都会调用服务器;但是,选择列表并未被填充。
最佳答案
将 return 语句添加到 CustomerService get 方法中,并删除您在 getAll()、getProduction()、getTest() 方法中编写的成功函数
surchargeIndex.service('customerService', [
"$http", function ($http) {
this.get = function (customerType) {
var promise;
if (customerType == "1") {
promise = getProduction().then(function (result) { return result.data; });
} else if (customerType == "2") {
promise = getTest().then(function (result) { return result.data; });
} else {
promise = getAll().then(function (result) { return result.data; });
}
return promise;
}
var getTest = function () {
return $http({
method: "GET",
url: "api/Customer/GetTest",
});
};
var getProduction = function () {
return $http({
method: "GET",
url: "api/Customer/GetProduction",
});
};
var getAll = function () {
return $http({
method: "GET",
url: "api/Customer/GetAll",
});
};
Controller
$scope.getCustomers = function(customerType) {
$scope.showContent = false;
customerService.get(customerType).then(function(data) {
$scope.customers = data;
});
};
关于javascript - 如何正确返回 Angular 服务的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27944960/