我已经设置了一个控制器和服务来从我自己的 NodeJS API/MongoDB 端点获取一些 JSON。
在我的浏览器控制台中,我看到一个返回的对象和 5 个项目,当我查询我的 api 时,我在浏览器中看到相同的 json,所以我知道它在服务器端工作。
我很困惑为什么当尝试通过这个进行 NG-Repeat 时我在页面上什么也没有,当我控制台注销返回的数据时,它返回未定义。
我是 HTTP 模块的新手,我正在尝试重构对服务的数据库调用,而不是在控制器中使用它。
--- 控制器代码 ---
vm.getDepartments = function() {
vm.departments = DbService.getAllDepartments();
console.log(vm.departments);
}();
--- 服务代码(使用 $http)---
function getAllDepartments() {
$http.get('/api/departments').then(function(err, response) {
if (err) {
console.log(err);
}
return response;
});
};
--- html 页面 ---
<tbody>
<tr ng-repeat='dept in vm.departments'>
<td>{{ dept.departmentLong }}</td>
<td>{{ dept.departmentShort }}</td>
<td>
<button class='btn btn-warning'><span class='glyphicon glyphicon-edit'></span></button>
<button class='btn btn-danger' ng-click='vm.deleteDepartment(dept);'><span class='glyphicon glyphicon-ban-circle'></span></button>
</td>
</tr>
</tbody>
你用错了then
方法。
该then()
方法有两个参数:asuccess
和一个error
回调,它将被一个response
对象调用。
使用该then()
方法,将callback
函数附加到返回的promise
.
$http.get('/api/departments')
返回一个promise,因此您可以创建一个仅返回 promise 的函数,正如@sachila ranawaka 所提到的。
function getAllDepartments() {
return $http.get('/api/departments')
};
在控制器中使用我上面提到的then方法。
DbService.getAllDepartments().then(function(response) {
vm.departments = response.data;
console.log(vm.departments);
},function(error){
console.log(err);
});
另一种方法是创建一个callback
函数,并将其传递给getAllDepartments
方法。
function getAllDepartments(callback) {
$http.get('/api/departments').then(function(response) {
callback(response);
});
};
控制器代码:
vm.getDepartments = function() {
vm.departments = DbService.getAllDepartments(function(result){
console.log(result);
});
}();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句