在AngularJS中,我似乎無法理解'promise'的概念,我使用restangular庫通過REST獲取資源,但是我總是得到空結果。下面的代碼在angularjs中使用延遲結果
.service('CareersService', [ 'Restangular', '$sce', function(Restangular, $sce){
var vacancies = [];
var result;
this.getVacancies = function() {
Restangular.all('job_posts').getList({active: 'true'}).then(function(job_posts){
job_posts.forEach(function(job_post){
vacancies.push(_.pick(job_post,['id','title','min_experience','max_experience','location']));
})
})
return vacancies;
}
this.getVacancy = function(job_id){
Restangular.one('job_posts',job_id).get().then(function(job_post){
result = _.pick(job_post, 'title','min_experience','max_experience','location','employment_type','description');
var safe_description = $sce.trustAsHtml(result.description);
var emp_type = _.capitalize(result.employment_type);
_.set(result, 'description', safe_description);
_.set(result, 'employment_type', emp_type);
});
return result;
}
}]).controller('DetailsCtrl', ['$scope' ,'$stateParams', 'CareersService' ,function($scope, $stateParams, CareersService) {
$scope.data.vacancy = { title: 'Loading ...', contents: '' };
$scope.data.vacancy = CareersService.getVacancy($stateParams.job_id);
}])
,然後在視圖
<div class="container">
<a ui-sref="careers" class="btn btn-primary">Show All</a>
<div class="row">
<h2>{{ data.vacancy.title }}</h2>
<p>{{ data.vacancy.min_experience }}</p>
<p>{{ data.vacancy.max_experience }}</p>
<p>{{ data.vacancy.location }}</p>
<p>{{ data.vacancy.employment_type }}</p>
<p ng-bind-html="data.vacancy.description"></p>
</div>
</div>
我缺少的東西在使用承諾的方式?
更新
這裏是更新的代碼感謝我來到這裏的所有幫助,
this.getVacancies = function() {
Restangular.all('job_posts').getList({active: 'true'}).then(function(job_posts){
job_posts.forEach(function(job_post){
vacancies.push(_.pick(job_post,['id','title','min_experience','max_experience','location']));
})
return vacancies;
})
}
this.getVacancy = function(job_id){
Restangular.one('job_posts',job_id).get().then(function(job_post){
vacancy = _.pick(job_post, 'title','min_experience','max_experience','location','employment_type','description');
...
return vacancy;
});
}
}])
並在控制器
CareersService.getVacancy($stateParams.job_id).then(function (vacancy){
$scope.data.vacancy = vacancy;
});
和
CareersService.getVacancies().then(function (vacancies){
$scope.data.vacancies = vacancies;
});
我現在得到的錯誤
Cannot read property 'then' of undefined
在生產線
CareersService.getVacancies().then(function(vacancies) {
你註銷了什麼空缺包含?並且還讓你感到沮喪並檢查你是否獲得了服務中的數據? –
有一個對服務的調用,並且成功(現在是304)響應,所以數據肯定被填充到job_post中。不知道爲什麼結果沒有被填充。未定義它表示當我在返回之前登錄到控制檯時。對於JS和Angular來說,這是一個不錯的選擇,所以甚至無法找出一個好的失敗測試,否則也會分享這個測試 –
''return'vacancies/result' ** **之前** .then()調用:[爲什麼我的變量在函數內部修改後沒有改變? - 異步代碼引用](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Andreas