我尝试使用$ http的方法,因为我的代码在请求结果返回之前运行。所以我的响应参数是未定义的。
var reqgetcustomers = $http({
url: 'api/customers/GetNbCustomer',
params: {
'lastName': lastName,
'firstName': firstName,
'address': address,
'town': town,
'zipCode': zipCode,
'skip': -1,
'take': -1
}
};
reqgetcustomers.then(function (dataresult) {
$scope.itemCount = dataresult.data;
var nbPage = Math.ceil($scope.itemCount / $scope.numPerPage);
locker.put('nbPage', nbPage);
console.log('locker nbPage before=> ', locker.get('nbPage'));
console.log('itemCount => ', $scope.itemCount);
});
我之后使用请求的结果,但是nbPage变量未定义。
欢迎任何帮助。
感谢。
答案 0 :(得分:0)
我成功了。这是我的新代码,如果它可以帮助某人:
//create the promise
function getCustomersRequest(lastName, firstName, address, town, zipCode, skip, take)
{
var deferred = $q.defer();
var reqgetcustomers = $http({
url: 'api/customers/GetNbCustomer',
params: {
'lastName': lastName,
'firstName': firstName,
'address': address,
'town': town,
'zipCode': zipCode,
'skip': -1,
'take': -1
}
});
reqgetcustomers.success(function (dataResult) {
deferred.resolve(dataResult);
});
return deferred.promise;
}
//new method with promise
function GetListFiltered(lastName, firstName, address, town, zipCode, skip, take) {
var deferred = $q.defer();
var reqSearchCustomers = $http({
url: '/api/customers/GetFilteredList',
params: {
'lastName': lastName,
'firstName': firstName,
'address': address,
'town': town,
'zipCode': zipCode,
'skip': skip,
'take': take
}
});
reqSearchCustomers.success(function (dataResult) {
deferred.resolve(dataResult);
$scope.customers = dataResult;
});
var myPromise = getCustomersRequest(lastName, firstName, address, town, zipCode, skip, take);
myPromise.then(function (resolve) {
$scope.itemCount = resolve;
locker.put('itemCount', resolve);
locker.put('skip', ((locker.get('currentPage') - 1) * $scope.numPerPage));
var nbPage = Math.ceil(locker.get('itemCount') / $scope.numPerPage);
locker.put('nbPage', nbPage);
$scope.skip = locker.get('skip');
$scope.nbPage = locker.get('nbPage');
}
GetListFiltered(locker.get('lastName'), locker.get('firstName'), locker.get('address'), locker.get('town'), locker.get('zipCode'), $scope.skip, $scope.numPerPage);