在客户端使用AngularJS进行HTTP请求
成功完成本教程后 ,我开始构build我的应用程序路由,以处理在数据库中创build的一些虚拟模型,当我通过Postman应用程序请求它们时(使用以下URL:https://lab4-roger13.c9users .IO:8080 / API /书呆子)。
下一步是在AngularJS中创build一个服务,允许用户在客户端请求这些相同的信息。 在教程结束时,我留下了这个:
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的服务属性,该符号显示2.但是,当我尝试与get
属性相同时,什么都不显示。
我不确定,这个教程在$http.get
提供的URL是错误还是我错过了一个步骤来访问GET响应?
(如果我错过了任何相关的代码,它们与教程链接中的相同 )
Nerd.get()
是一个函数,它从$http
服务返回一个promise。 如果您想在视图中显示结果,可以将结果绑定到您的视图中,如下所示:
.controller('nerdDB', ['$scope', 'Nerd', function($scope, Nerd) { Nerd.get().then(function(nerds) { $scope.nerds = nerds; }); }]);
喜欢这个post我有一些问题,使用工厂,发现解决scheme这里书呆子控制器
angular.module('NerdCtrl', []).controller('NerdController', function($scope, Nerd) { $scope.tagline = 'bla bla'; $scope.nerds = {}; Nerd.getNerd() .then(function (components) { $scope.nerds = components; }, function (error) { console.error(error); }); });
作为服务
angular.module('NerdService', []).factory('Nerd', function ($q, $http) { return { getNerd: function () { var deferred = $q.defer(), httpPromise = $http.get('/api/nerds'); httpPromise.success(function (components) { deferred.resolve(components); }) .error(function (error) { console.error('Error: ' + error); }); return deferred.promise; } }; });
在NerdHTLM中使用控制器来循环logging
<table ng-controller="NerdController" > <tbody> <tr ng-repeat="nerd in nerds"> <td>{{nerd.name}}</td> <td>{{nerd.type}}</td> </tr> </tbody> </table>