【发布时间】:2016-02-27 11:04:14
【问题描述】:
在成功完成this tutorial 之后,我开始构建我的应用程序路由来处理在数据库中创建一些虚拟模型,当我通过 Postman 应用程序请求它们时,它工作得很好(使用以下 URL:https://lab4 -roger13.c9users.io:8080/api/nerds)。
下一步是在 AngularJS 中创建一个服务,以允许用户在客户端请求相同的信息。在教程结束时,我得到了这个:
angular.module('NerdService', []).factory('Nerd', ['$http', function($http) {
return {
// call to get all nerds
get : function() {
return $http.get('/api/nerds');
},
a : 2,
// these will work when more API routes are defined on the Node side of things
// call to POST and create a new nerd
create : function(nerdData) {
return $http.post('/api/nerds', nerdData);
},
// call to DELETE a nerd
delete : function(id) {
return $http.delete('/api/nerds/' + id);
}
}
}]);
这是链接我所有服务和路线的模块:
angular.module('sampleApp',
['ngRoute', 'appRoutes', 'MainCtrl', 'NerdCtrl', 'NerdService'])
.controller('nerdDB', ['$scope', 'Nerd', function($scope, Nerd) {
$scope.a = Nerd.a;
}]);
这是我尝试访问的后端路由示例:
module.exports = function(app) {
// get all nerds in the database (accessed at GET https://lab4-roger13.c9users.io:8080/api/nerds)
app.get('/api/nerds', function(req, res) {
// use mongoose to get all nerds in the database
Nerd.find(function(err, nerds) {
// if there is an error retrieving, send the error.
// nothing after res.send(err) will execute
if (err)
res.send(err);
res.json(nerds); // return all nerds in JSON format
});
});
如您所想,我可以使用 {{a}} 表示法访问 html 中服务的 a 属性,该符号显示 2。但是当我尝试使用 get 属性时,没有任何显示.
我不确定,教程在$http.get 提供的 URL 是错误的还是我错过了访问 GET 响应的步骤?
(如果我遗漏了任何相关代码,它们与可以在tutorial link 找到的代码相同)
【问题讨论】:
-
get返回一个函数,而不是静态属性。
标签: angularjs node.js http crud