在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